How to avoid a for loop in functions?

1 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2020-2-18
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by