How to avoid a for loop in functions?

11 vues (au cours des 30 derniers jours)
Prasanna
Prasanna le 18 Fév 2020
Commenté : Star Strider le 19 Fév 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

Réponse acceptée

Star Strider
Star Strider le 18 Fév 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 commentaires
Prasanna
Prasanna le 19 Fév 2020
Thanks Star Strider. That helped.
Star Strider
Star Strider le 19 Fév 2020
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by