How can I change for-loop into matrix way?
조회 수: 1 (최근 30일)
이전 댓글 표시
I'd like to vectorize the for-loop below, but cannot come up with any idea. Could you help me?
for i=1:100
for j=1:1000
A(i+1,j)= B(find(C(B==A(i,j),:,D==E(i))>F(i,j),1));
end
end
채택된 답변
Matt J
2021년 6월 8일
This gives some speed-up.
%Fake Data
m=100;n=1000;
B=rand(15,1);
D=rand(3,1);
A=B(randi(15,m+1,n));
E=D(randi(3,m+1,1));
C=rand(15,15,3);
F=0.3*ones(size(A));
%Original version
tic;
for i=1:m
for j=1:n
A(i+1,j)= B(find(C(B==A(i,j),:,D==E(i))>F(i,j),1));
end
end
toc
A1=A;
%Proposed version
tic;
locD=(1:3)*(D==E.');
for i=1:m
Ai=A(i,:);
Ei=E(i);
Fi=F(i,:);
[~,locB]=ismember(Ai,B);
[~,idx]=max( C(locB,:,locD(i))>Fi(:) ,[],2);
A(i+1,:)= B(idx);
end
toc
A2=A;
isequal(A1,A2)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!