MATLAB Language Vectorization Element-wise operations


MATLAB supports (and encourages) vectorized operations on vectors and matrices.
For example, suppose we have A and B, two n-by-m matrices and we want C to be the element-wise product of the corresponding elements (i.e., C(i,j) = A(i,j)*B(i,j)).

The un-vectorized way, using nested loops is as follows:

C = zeros(n,m);
for ii=1:n
    for jj=1:m
        C(ii,jj) = A(ii,jj)*B(ii,jj);

However, the vectorized way of doing this is by using the element-wise operator .*:

C = A.*B;

  • For more information on the element-wise multiplication in MATLAB see the documentation of times.
  • For more information about the difference between array and matrix operations see Array vs. Matrix Operations in the MATLAB documentation.