MATLAB Language Vectorization Element-wise operations

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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);
    end
end

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.


Got any MATLAB Language Question?