Clear Filters
Clear Filters

How to optimize this for loop?

1 view (last 30 days)
Prakash Choudhary
Prakash Choudhary on 10 May 2019
Answered: Bob Thompson on 10 May 2019
% % % % --------------------
for i=1:size(v0)
if (v0(i)<=2)
v0(i) = 0;
else
if (v0(i) >= 12 && v0(i) <= 25)
v0(i) = 12;
else
if (v0(i) >= 26)
v0(i) = 0;
end
end
end
end
% condition for another wind speed
for i=1:size(v0)
if (v1(i)<=2)
v1(i) = 0;
else
if (v1(i) >= 12 && v1(i) <= 25)
v1(i) = 12;
else
if (v1(i) >= 26)
v1(i) = 0;
end
end
end
end
% conditon for another wind didrection
for i=1:size(v0)
if (v2(i)<=2)
v2(i) = 0;
else
if (v2(i) >= 12 && v2(i) <= 25)
v2(i) = 12;
else
if (v2(i) >= 26)
v2(i) = 0;
end
end
end
end

Answers (1)

Bob Thompson
Bob Thompson on 10 May 2019
v0(v0<=2) = 0;
v0(v0>=26) = 0;
v0(v0>=120) = 12;
Should work for all three, because they're apparently the same with different labels? If they're all the same size I would strongly suggest avoiding using dynamically named variables. You can just concatenate them into a single matrix with another dimension. For example, if they are a single dimension, then they combine to a 2D matrix that you can loop through the second dimension on (not that you have to because you're looking for the same conditions and outputs. Then you only have to use the above code once, instead of three times.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!