How to access the equation above the while loop

1 回表示 (過去 30 日間)
Stark Volt
Stark Volt 2021 年 9 月 17 日
コメント済み: Stark Volt 2021 年 9 月 20 日
How to access the y and limit equation above the while loop so that i do not need to type the equation inside the while loop?
y = 0;
limit= (exp(y)-(1+y+y^2/2+y^3/6))/exp(y)
while y>=0
y=y+0.01;
limit=(exp(y)-(1+y+y^2/2+y^3/6))/exp(y);
if limit>0.01
break
end
end
y=y

採用された回答

the cyclist
the cyclist 2021 年 9 月 17 日
編集済み: the cyclist 2021 年 9 月 17 日
One straightforward way to do this is by using an anonymous function:
% Define an anonymous function for the limit
f_limit = @(y) (exp(y)-(1+y+y^2/2+y^3/6))/exp(y);
y = 0;
limit = f_limit(y)
while y>=0
y=y+0.01;
limit = f_limit(y);
if limit>0.01
break
end
end
y = y
  3 件のコメント
the cyclist
the cyclist 2021 年 9 月 18 日
I don't understand why you need another way.
Can you please explain in more detail what you need, and why your solution (with my modification) is not ideal?
Stark Volt
Stark Volt 2021 年 9 月 18 日
Ah sorry for that, your solution is good, I just want to see other types of solution and somehow learn from them just like the (anonymous function) I did not know this until you shown it me. Thanks

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2021 年 9 月 18 日
Try this:
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format short g;
format compact;
fontSize = 20;
y = 0;
limit = CustomFunction(y)
loopCounter = 1; % Failsafe to prevent infinite loop
maxIterations = 1000; % Failsafe - way more than you think you'll ever need.
while y >= 0 && loopCounter < maxIterations
fprintf('On iteration #%d, y = %f and limit = %f.\n', loopCounter, y, limit);
y = y + 0.01;
limit = CustomFunction(y);
if limit > 0.01
break
end
loopCounter = loopCounter + 1;
end
% Define a function for the limit
function f_limit = CustomFunction(y)
f_limit = (exp(y)-(1+y+y^2/2+y^3/6))/exp(y);
end
Put it all into one m-file, like test.m or whatever (don't call it limit.m or f_limit.m). You'll see
On iteration #1, y = 0.000000 and limit = 0.000000.
On iteration #2, y = 0.010000 and limit = 0.000000.
On iteration #3, y = 0.020000 and limit = 0.000000.
....
On iteration #80, y = 0.790000 and limit = 0.008702.
On iteration #81, y = 0.800000 and limit = 0.009080.
On iteration #82, y = 0.810000 and limit = 0.009469.
On iteration #83, y = 0.820000 and limit = 0.009868.
  1 件のコメント
Stark Volt
Stark Volt 2021 年 9 月 20 日
I also like your way, but (the cyclist) was the first to comment. Thats why I voted for your answer, Thanks

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by