Wednesday, March 17, 2010

Matlab: operate on matched dimension with different shaped matrices

OP.

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:3
for k2 = 1:2
c = c+1;
p(:,c) = a(:,k1).*b(:,k2);
end
end

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.

1 comment:

altered said...
This comment has been removed by the author.