Running a while loop one time after the parameter is met

10 ビュー (過去 30 日間)
Logan
Logan 2023 年 2 月 22 日
編集済み: Aditya Srikar 2023 年 3 月 2 日
The problem is to write a code that will approximate the slope of an equation at a point by using the value of the function at a point x and a point xi. The slope is being approximated by using f(xi)-f(x)/xi-x. X is randomly generated, and the increment between the points x and xi is to be 1 at first, and to be halved each loop until two consecutive slope approximations are within 1% of each other. My issue is that I got the code to loop until f(xi) is within 1% of f(x), but I don't know how to phrase my condition or nest another statement to get the loop to run one more time to satisfy the requirement of two consecutive approximations being within 1% of each other. I "manually" ran the sequence one more time after the while loop to obtain the correct answer, but I know that I should be able to do it within a single loop.
x=rand*9+1;
n=1; % increment
xi=x+n;
y=(5*x^2)/(log10(7*x^4)); % function to approximate slope of
yi=(5*xi^2)/(log10(7*xi^4));
while ((yi-y)/y)>0.01
n=n/2;
xi=x+n;
yi=(5*xi^2)/(log10(7*xi^4));
end
n=n/2;
xi=x+n;
yi=(5*xi^2)/(log10(7*xi^4));
slope=(yi-y)/(xi-x)
  1 件のコメント
Askic V
Askic V 2023 年 2 月 22 日
編集済み: Askic V 2023 年 2 月 22 日
Hello Logan,
please have a look at this thread:
Basically you need this:
while true
n=n/2;
xi=x+n;
yi=(5*xi^2)/(log10(7*xi^4));
if (yi-y)/y<=0.01
break
end
end

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

採用された回答

Aditya Srikar
Aditya Srikar 2023 年 3 月 2 日
編集済み: Aditya Srikar 2023 年 3 月 2 日
Hi Logan
The condition in while loop need to be
(yi-y)/y<=0.01
Modify the condition and the code should work fine.
I hope this helps

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by