vectorize two nested for loops in matlab

Suppose you have two nested For loops over matrices A and B in MATLAB which looks like:

main.m
for i=1:size(A,1)
    for j=1:size(B,2)
        % do some operation with A(i,:) and B(:,j)
    end
end
103 chars
6 lines

To vectorize this code:

main.m
[m,n]=size(A);
[p,q]=size(B);
%reshaping of A and B matrices into vectors
A_reshaped=reshape(A,[m*n,1]);
B_reshaped=reshape(B,[1,p*q]);
%creating a matrix of size(m*n,p*q) by multiplying reshaped A and B vectors
C = A_reshaped * B_reshaped;
%reshaping back the resultant matrix into a matrix of size(m,q)
C_final=reshape(C,[m,q]);
331 chars
10 lines

In this way, we have eliminated the two nested For loops and converted to a vectorized form. This vectorized implementation leads to faster execution times due to efficient use of matrix operations.

gistlibby LogSnag