2 'for loop':
i=1;
j=1;
n=5;
a=[1 2 3 4 5; 6 7 8 9 10; 1 2 3 4 5; 6 7 8 9 10; 1 2 3 4 5;];
for i=1:n
for j=1:n
a(i,j) = a(i,j)./n;
end
end
disp(a)
1 'for loop':
i=1;
j=1;
n=5;
a=[1 2 3 4 5; 6 7 8 9 10; 1 2 3 4 5; 6 7 8 9 10; 1 2 3 4 5;];
for i=1:n
a(i,j:n) = a(i,j:n)./n;
end
disp(a)
0 'for loop':
i=1;
j=1;
n=5;
a=[1 2 3 4 5; 6 7 8 9 10; 1 2 3 4 5; 6 7 8 9 10; 1 2 3 4 5;];
a(i:n,j:n) = a(i:n,j:n)./n;
disp(a)
In all the above cases, the results are the same. You may run the codes and check for yourself. The operation is pretty straightforward here. When colon (:) is first used between j and n, we eliminate a 'for loop'. This colon (:) is considering all the elements in columns of the matrix a, which is equivalent to the 'loop' operation. The second colon (:), between i and n (i:n), takes all the row elements of the matrix a, and the operation is also same compared to using a 'for loop'. Below is the result for all three demonstrated cases.
0.2000 0.4000 0.6000 0.8000 1.0000
1.2000 1.4000 1.6000 1.8000 2.0000
0.2000 0.4000 0.6000 0.8000 1.0000
1.2000 1.4000 1.6000 1.8000 2.0000
0.2000 0.4000 0.6000 0.8000 1.0000
This is a very simple example, and for this, you won't even realize the actual computational efficiency. But, imagine! you have very large matrices where numerous complex operations involved. In that case, you would be able to see the differences.
#Vectorization #Matrix #ForLoop #UseofColon #Matlab #Blog #Blogger
No comments:
Post a Comment