Matrix Multiplication Along Pages of Multidimensional Matrix

4 ビュー (過去 30 日間)
Mark Whirdy
Mark Whirdy 2014 年 8 月 27 日
コメント済み: Mark Whirdy 2014 年 8 月 27 日
What is the most efficient way of matrix-multiplying along a page (2d plane) of a multidimensional matrix. Speed is important here as this operation will be in the objective-function of a calibration.
Specifically I have a 4d matrix of dimension [m,n,p,2], and I want to matrix-multiply it by a [2x1] vector
So conceptually I need
b*y0'
Taking for example:
b = rand(5,3,4,2); %
y0 = [0.1;0.2]; y0 = reshape(y0,[1,1,1,2]); %
I should end up with a 3d matrix of size [5,3,4]
I could, of course, dot-multiply by a repmatted y0 and then sum along the 4d but is this really the most efficient?
y0 = y0(ones(5,1,1),ones(1,3,1),ones(1,1,4),:);
sum(b.*y0,4);
All the best

採用された回答

Matt J
Matt J 2014 年 8 月 27 日
If size(b,4)=2 all the time, it would probably be best just to generate two separate 3D arrays b1 and b2
result=b1*y0(1)+b2*y0(2);
  2 件のコメント
Matt J
Matt J 2014 年 8 月 27 日
Note, this is different from (and faster than)
result=b(:,:,:,1)*y0(1)+b(:,:,:,2)*y0(2);
Mark Whirdy
Mark Whirdy 2014 年 8 月 27 日
you're right - talk about overengineering :-D
thanks!

サインインしてコメントする。

その他の回答 (2 件)

Matt J
Matt J 2014 年 8 月 27 日
編集済み: Matt J 2014 年 8 月 27 日
I could, of course, dot-multiply by a repmatted y0 and then sum along the 4d but is this really the most efficient?
Probably, if you're stuck with b in the shape you describe. However, it is better to use bsxfun, rather than repmat;
y0 = [0.1;0.2]; y0 = reshape(y0,[1,1,1,2]); %
result = sum( bsxfun(@times, b,y0) , 4)
  3 件のコメント
Matt J
Matt J 2014 年 8 月 27 日
It's not a meaningful test with m,n,p that small. If your dimensions are truly that size, you should be thinking about vectorizing across the different batches of b.
Mark Whirdy
Mark Whirdy 2014 年 8 月 27 日
[4000,10,2,2] is the real size

サインインしてコメントする。


Matt J
Matt J 2014 年 8 月 27 日
編集済み: Matt J 2014 年 8 月 27 日
If you can re-organize the code that generates b so that, without using permute() , it is instead 2 x m x n x p , that would be ideal. You can then do it all by straight matrix multiplication
result=squeeze( y0.'*reshape(b,2,[]) );

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by