Adding each row of a matrix to another matrix
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
SciFiPhysics Guy
el 21 de Abr. de 2022
Comentada: SciFiPhysics Guy
el 22 de Abr. de 2022
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 comentarios
Image Analyst
el 21 de Abr. de 2022
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.
Respuesta aceptada
Voss
el 21 de Abr. de 2022
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 comentarios
Voss
el 22 de Abr. de 2022
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)
Más respuestas (0)
Ver también
Categorías
Más información sobre Linear Algebra en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!