How can I change for-loop into matrix way?

8 views (last 30 days)
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
  9 Comments
icdi
icdi on 8 Jun 2021
Edited: icdi on 8 Jun 2021
Yes all of your points are right.
D is 3x1. For all i and j, A(i,j) is supposed to have one of elements of B, and E(i) also has one of elements of D. So this code can give the series of numbers between 1 and 15.
Matt J
Matt J on 8 Jun 2021
Edited: Matt J on 8 Jun 2021
So the elements of B and D are all unique? Also, what is supposed to happen if find() returns empty [], i.e., if
C(B==A(i,j),k,D==E(i)) < F(i,j)
for all k=1...15?

Sign in to comment.

Accepted Answer

Matt J
Matt J on 8 Jun 2021
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
Elapsed time is 0.372233 seconds.
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
Elapsed time is 0.050406 seconds.
A2=A;
isequal(A1,A2)
ans = logical
1
  1 Comment
icdi
icdi on 8 Jun 2021
Thanks! Your code works very well and saves me time. Thanks again.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!