All possible combinations of adding two matrices elementwise

I want to calculate all possible combinations of adding elements in two NxN matrices, resulting in a NxNxNxN (or N^2xN^2) matrix. My current method uses 4 for-loops, like "sum(i,j,k,l)=A(i,j)-B(k,l), where i,j,k,l=1:N ", but it is quite time-consuming and I'm guessing using matrix multiplication in some way would be more effective, but I can't figure how to do it.

 採用された回答

John D'Errico
John D'Errico 2017 年 12 月 9 日
編集済み: John D'Errico 2017 年 12 月 9 日

1 投票

Easy, peasy, that is, IF you have a current MATLAB release. A one line solution...
A = rand(2,2)
A =
0.37803 0.80787
0.21181 0.90728
B = [1 2;3 4];
C = A + reshape(B,[1 1, size(A)])
C(:,:,1,1) =
1.378 1.8079
1.2118 1.9073
C(:,:,2,1) =
3.378 3.8079
3.2118 3.9073
C(:,:,1,2) =
2.378 2.8079
2.2118 2.9073
C(:,:,2,2) =
4.378 4.8079
4.2118 4.9073
size(C)
ans =
2 2 2 2

2 件のコメント

Linus Kron
Linus Kron 2017 年 12 月 9 日
great, exactly what i needed!
Andrei Bobrov
Andrei Bobrov 2017 年 12 月 9 日
+1

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

その他の回答 (2 件)

Matt J
Matt J 2017 年 12 月 9 日

0 投票

You can use my tensorsum function
reshape(tensorsum(A,B),[N,N,N,N]);
where
function X = tensorsum(A,B)
%TENSORSUM
%
% Modification of Laurent Sorber's KRON
[I J] = size(A);
[K L] = size(B);
if ~issparse(A) && ~issparse(B)
A = reshape(A,[1 I 1 J]);
B = reshape(B,[K 1 L 1]);
X = reshape(bsxfun(@plus,A,B),[I*K J*L]);
else
[ia,ja,sa] = find(A); ia=ia(:); ja=ja(:); sa=sa(:);
[ib,jb,sb] = find(B); ib=ib(:); jb=jb(:); sb=sb(:);
ix = bsxfun(@plus,K*(ia-1).',ib);
jx = bsxfun(@plus,L*(ja-1).',jb);
X = sparse(ix,jx,bsxfun(@plus,sb,sa.'),I*K,J*L);
Matt J
Matt J 2017 年 12 月 9 日
編集済み: Matt J 2017 年 12 月 9 日

0 投票

In R2016b and higher you could also just do this
out = reshape(B(:)+A(:).', [N,N,N,N]);
It will give a somewhat different order than my previous answer

カテゴリ

ヘルプ センター および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by