I have 3 different matrices, Say [A] [B] and [C]. Each matrix A, B and C is of size 8×3 i.e. 24 elemnts each.

Final desired output is a column vector which has total of 24x24x24= 13824 elements, in the following order:

A(1,1)*B(1,1)*C(1,1)

…

A(1,1)*B(1,1)*C(8,1)

A(1,1)*B(2,1)*C(1,1)

…

A(1,1)*B(2,1)*C(8,1)

…

A(8,1)*B(8,1)*C(8,1)

A(1,1)*B(1,1)*C(1,2)

…

A(1,1)*B(1,1)*C(8,2)

…

A(8,3)*B(8,3)*C(8,3)

Currently I am using 6 nested loops (3 loops which run over the 3 columns of each matrix A B and C, and 3 loops for every row of matrices A, B and C)

counterNp=1;

for a1=1:3

for a2=1:3

for a3=1:3

for b1=1:8

for b2=1:8

for b3=1:8

V(counterNp)= A(b1,a1)*B(b2,a2)*C(b3,a3);

counterNp=counterNp+1;

end

end

end

end

end

end

I get the desired output this way, but the problem is it's computationally very expensive for the actual calculations that I am doing (the above example is a simplified version), it takes my code 17 hours to run this calculation.

I am wondering if someone can help me with vectorizing this code.

I was thinking of using bsxfun(@times,A,B'). and then repeat this multiple times, are there better ways?

Thanks

## Best Answer