Adding each row of a matrix to another matrix
조회 수: 2 (최근 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!