How to avoid a for loop in functions?
1 view (last 30 days)
Show older comments
Hi All,
I have the following for loop in my matlab code and I was wandering is there any effcient way to implement this than using a for loop and going through each element.
press = 0:5/1000:5;
PsolWB = [];
for i = 1:length(press)
if (press(i)<=1.6)
PsolWB(i) = (973.-(70400./(1000.*press(i)+354.))+(77800000./(1000.*press(i)+354.).^2.)-273.15);
else
PsolWB(i)=(935.+3.5.*press(i)+6.2.*press(i).^2-273.15);
end
end
0 Comments
Accepted Answer
Star Strider
on 18 Feb 2020
Use ‘logical indexing’ and anonymous functions to eliminate the for loop and the if block:
PsolWB1 = @(press) (973.-(70400./(1000.*press+354.))+(77800000./(1000.*press+354.).^2.)-273.15);
PsolWB2 = @(press) (935.+3.5.*press+6.2.*press.^2-273.15);
PsolWB = @(press) PsolWB1(press).*(press <= 1.6) + PsolWB2(press).*(press > 1.6);
press = 0:5/1000:5;
figure
plot(press, PsolWB(press))
grid
This takes advantage of MATLAB’s vectorisation capabilities.
The plot is simply to demonstrate the result. It is not necessary for the code.
2 Comments
More Answers (0)
See Also
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!