Created
October 30, 2011 23:48
-
-
Save adilsoncarvalho/1326603 to your computer and use it in GitHub Desktop.
Matlab script showing how to use vectoralization to avoid iterations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% | |
% Suppose you have three vector valuated variables, u, v and w: | |
% | |
% +- -+ | |
% | u1 | | |
% u = | u2 | | |
% | u3 | | |
% +- -+ | |
% | |
% +- -+ | |
% | v1 | | |
% v = | v2 | | |
% | v3 | | |
% +- -+ | |
% | |
% +- -+ | |
% | w1 | | |
% w = | w2 | | |
% | w3 | | |
% +- -+ | |
% | |
% and you wanna compute u(j) = 2 * v(j) + 5 * w(j) | |
% | |
display(' ') | |
display('VECTORALIZATION STUDY') | |
display(' ') | |
% let's initializa the data vectors | |
v = [ 11; 22; 33 ]; | |
w = [ 100; 200; 300 ]; | |
u_for = zeros(3,1); | |
u_vec = zeros(3,1); | |
% ------------------------------------- | |
% you can do that using a for statement | |
for j = 1:3, | |
u_for(j) = 2 * v(j) + 5 * w(j); | |
end | |
display('Value of u (throught for)'); | |
display(u_for); | |
% --------------------------------------------- | |
% you can achieve that throught vectoralization | |
u_vec = 2 * v + 5 * w; | |
display('Value of u (throught vectoralization)'); | |
display(u_vec); | |
% assert that verifies the result | |
if u_for == u_vec, | |
display('Success'); | |
else | |
display('Failure'); | |
end | |
% graphical user assertion to verify the result | |
subplot(1,2,1), hist(u_for), title('FOR'); | |
subplot(1,2,2), hist(u_vec), title('VECTORIZED'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment