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.

 Accepted Answer

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

More Answers (2)

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);
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

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!