How to avoid a for loop in functions?
11 ビュー (過去 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
0 件のコメント
採用された回答
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.
2 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!