How to avoid a for loop in functions?

1 Ansicht (letzte 30 Tage)
Prasanna
Prasanna am 18 Feb. 2020
Kommentiert: Star Strider am 19 Feb. 2020
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

Akzeptierte Antwort

Star Strider
Star Strider am 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 Kommentare
Prasanna
Prasanna am 19 Feb. 2020
Thanks Star Strider. That helped.
Star Strider
Star Strider am 19 Feb. 2020
As always, my pleasure!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by