MATLAB: All possible combinations of adding two matrices elementwise

combinationsmatrix operations

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.

Best 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