Adding each row of a matrix to another matrix
5 ビュー (過去 30 日間)
古いコメントを表示
Is there a linear operation for adding the individual rows of a matrix to another matrix, something like a tensor product but for summing? if not, would repmat be better here? This is my implimentation:
For a numeric Example:
A1 =rand(4, 2);
A2 =rand(2, 2);
A12=zeros(size(A1,1)*size(A2,1),size(A1,2));
startind=1+size(A1,1)*(0:(size(A2,1)-1));
endind=startind+size(A1,1)-1;
for i=1:size(A2,1)
A12(startind(i):endind(i),:)=A2(i,:)+A1;
end
For a symbolic Example:
A1 =sym('A1', [4 2]);
A2 =sym('A2', [2 2]);
A12=sym('A12', [size(A1,1)*size(A2,1),size(A1,2)]);
startind=1+size(A1,1)*(0:(size(A2,1)-1));
endind=startind+size(A1,1)-1;
for i=1:size(A2,1)
A12(startind(i):endind(i),:)=A2(i,:)+A1;
end
2 件のコメント
Image Analyst
2022 年 4 月 21 日
I don't have the symbolic toolbox so I'm not sure what you're doing, but wouldn't it just be
A12 = A1 + A1;
Give a small numerical example so we can see what you're starting with for A1 and A2, and what you'd like to end up with for A12.
採用された回答
Voss
2022 年 4 月 21 日
A1 =rand(4, 2);
A2 =rand(2, 2);
% the original method
A12=zeros(size(A1,1)*size(A2,1),size(A1,2));
startind=1+size(A1,1)*(0:(size(A2,1)-1));
endind=startind+size(A1,1)-1;
for i=1:size(A2,1)
A12(startind(i):endind(i),:)=A2(i,:)+A1;
end
A12_original = A12;
% another method
A12 = repmat(A1,size(A2,1),1)+repelem(A2,size(A1,1),1);
% check
isequal(A12,A12_original)
% another method
[ii,jj] = meshgrid(1:size(A2,1),1:size(A1,1));
A12 = A2(ii,:)+A1(jj,:);
% check
isequal(A12,A12_original)
3 件のコメント
Voss
2022 年 4 月 22 日
I'm not sure about an analogy to kron but for summation, but here's another way to do the operation in question (where the matrices have the same number of columns and the summation is done with all pairs of rows), this time with no indexing or repmat/repelem:
A1 = rand(4,2);
A2 = rand(2,2);
A12 = reshape(permute(A1,[1 3 2])+permute(A2,[3 1 2]),[],size(A1,2));
% check
A12_original = repmat(A1,size(A2,1),1)+repelem(A2,size(A1,1),1);
isequal(A12,A12_original)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Linear Algebra についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!