## Welcome to the World of Modelling and Simulation

### What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ...

### Vectorization in MATLAB: Use of Colon (:)

We are familiar with 'for loop' application in MATLAB. We may use many 'loops' to handle complex calculations. But, sometimes too many 'loops' cost computational time, which eventually affects the overall efficiency of the codings. In MATLAB, instead of looping, we may use the method of vectorization to skip some 'loops'. We may use the operator colon (:) in MATLAB to form vectors that alternately eliminates the 'loops'. Let's explain the method with a very simple example. For example, we would like to divide a square matrix (for our example, 5x5) with a scalar number. Below, there are three scenarios. At first, we can use 2 'for loops' to do the operation. Secondly, we can skip one 'for loop' by using a colon (:) for the columns of the matrix a. Finally, we can avoid all 'for loops', and use colons (:) for both rows and columns of the example matrix a.

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