How to operate with multidimensional arrays (Einstein summation)?

12 ビュー (過去 30 日間)
LuisGarcia
LuisGarcia 2017 年 12 月 5 日
編集済み: Matt J 2017 年 12 月 6 日
Let's imagine that I have an array of dimension 4 (A_ijkl) that I want to multiply with an array of dimension 2 (B_kl) to obtain an array of dimension 2 (C_ij; i.e., summing over indices k and l). What could be the most efficient (and clean) manner of doing so in Matlab?
And let's go one step further, what if we want to do C_ijxy=A_ijklxy * B_klxy ?
Thank you

採用された回答

Matt J
Matt J 2017 年 12 月 5 日
編集済み: Matt J 2017 年 12 月 5 日
You would reshape() to transform it to a 2D matrix multiplication. In the first case, this would be
A=rand(3,4,2,2);
B=rand(2,2);
C=reshape(A,12,4)*B(:);
C=reshape( C ,3,4);
For the latter case, you would have to permute() and reshape()
A=rand(3,4,2,2,6,5); B=rand(2,2,7,8);
Ap=permute(A,[1,2,5,6,3,4]);
Apr=reshape(Ap,[],4); Br=reshape(B,4,[]);
C=reshape(Arp*Br,[3,4,6,5,7,8]);
  6 件のコメント
LuisGarcia
LuisGarcia 2017 年 12 月 6 日
編集済み: LuisGarcia 2017 年 12 月 6 日
This is part of a larger code and using the GPU will be a mess. I'm amazed that there is no way to deal with such operations (other than using loops). But many thanks anyway!
Matt J
Matt J 2017 年 12 月 6 日
編集済み: Matt J 2017 年 12 月 6 日
Sorry, one other way just occurred to me:
A=rand(3,4,5,6,7,8); B=rand(5,6,7,8);
Ar=reshape(A, 3*4, 5*6 ,7,8);
Br=reshape(B, 1, 5*6 ,7,8);
p=Ar.*Br; %assumes at least R2016b, otherwise use p=bsxfun(@times, Ar,Br)
C=reshape(sum(p,2),[3,4,7,8]);

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by