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
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