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

2 views (last 30 days)
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.

Accepted Answer

Thiago Henrique Gomes Lobato
Edited: Thiago Henrique Gomes Lobato on 13 Sep 2020
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!