Add each row of a matrix consecutively to all the rows of other matrix where both have equal number of columns
7 次查看(过去 30 天)
显示 更早的评论
Vijay Shekhawat
,2020-9-13
编辑: Thiago Henrique Gomes Lobato
,2020-9-13
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.
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
Find more on Shifting and Sorting Matrices 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!