All possible combinations of adding two matrices elementwise
Show older comments
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
More Answers (2)
Matt J
on 9 Dec 2017
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
1 Comment
Linus Kron
on 9 Dec 2017
Categories
Find more on Operating on Diagonal Matrices 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!