Add each row of a matrix consecutively to all the rows of other matrix where both have equal number of columns

조회 수: 2 (최근 30일)
A=[1 2;3 4;5 6;7 8];
B=[1 1;2 2];
lA=length(A);
H=zeros(1,2);
for i=1:lA
H0=A(i,:) + B;
H=cat(1,H,H0);
end
H(1,:)=[];
Please suggest something without a loop.

채택된 답변

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020년 9월 13일
편집: Thiago Henrique Gomes Lobato 2020년 9월 13일
You can avoid the loop by using repeated indexing:
IndexesA = 1:size(A,1);
IndexesA = sort( [IndexesA,IndexesA] ); % IndexesA=[ 1 1 2 2 3 3 4 4]
Bexpanded= repmat(B,length(IndexesA)/2,1); % Expand matrix so the sum can be vectorized
H = A(IndexesA,:)+Bexpanded
H =
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Depending on the size of A this can be ca. 20x faster than the (almost) original loop:
A = randn(100,2);
B = randn(2,2);
tic
for idx=1:10000
lA=length(A);
H=zeros(lA*2,2); % I changed somethings to be a little faster
for i=1:lA
H0=A(i,:) + B;
%H=cat(1,H,H0);
H(1+2*(i-1):2*i,:)= H0;
end
%H(1,:)=[];
end
TimeLoop = toc
tic
for idx=1:10000
IndexesA = 1:size(A,1);
IndexesA = sort( [IndexesA,IndexesA] );
Bexpanded= repmat(B,length(IndexesA)/2,1);
H = A(IndexesA,:)+Bexpanded;
end
TimeVec = toc
TimeLoop =
1.7428
TimeVec =
0.0861

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by