Q: Suppose I have
a = [1 2 3; 7 8 9; 6 5 4];b = [7 5; 1 3; 9 4];
I want calculate the product between every column of a and b. Is there a vectorized way of this loop:
p = zeros(3,6);c = 0;for k1 = 1:3for k2 = 1:2c = c+1;p(:,c) = a(:,k1).*b(:,k2);endend
A:
[m,n] = size(a);p = bsxfun(@times,reshape(a,[m 1 n]),b);p = reshape(p,n,[]);
Note:
permute(a,[1 3 2]) has the same effect as reshape(a,[m 1 n]) , but reshape is much faster.