Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bsxfun-like for matrix product

I need to multiply a matrix A with n matrices, and get n matrices back. For example, multiply a 2x2 matrix with 3 2x2 matrices stacked as a 2x2x3 Matlab array. bsxfun is what I usually use for such situations, but it only applies for element-wise operations. I could do something like:

blkdiag(a, a, a) * blkdiag(b(:,:,1), b(:,:,2), b(:,:,3))

but I need a solution for arbitrary n - ?

like image 972
Itamar Katz Avatar asked Jan 13 '14 10:01

Itamar Katz


1 Answers

You can reshape the stacked matrices. Suppose you have k-by-k matrix a and a stack of m k-by-k matrices sb and you want the product a*sb(:,:,ii) for ii = 1..m. Then all you need is

sza = size(a);
b = reshape( b, sza(2), [] ); % concatenate all matrices aloong the second dim
res = a * b; 
res = reshape( res, sza(1), [], size(sb,3) ); % stack back to 3d
like image 63
Shai Avatar answered Sep 21 '22 17:09

Shai