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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by