フィルターのクリア

How to determine how a loop finishes

3 ビュー (過去 30 日間)
Chris
Chris 2013 年 11 月 18 日
回答済み: Chris 2013 年 11 月 18 日
Alright, so I have an assignment where I am to use the secant method to find the root of a function. I have the program written for the most part, and I'm able to find the root of a function no problem. However, I don't know how to have an output that can determine whether the loop finished because an answer was found, or if all the iterations were used and an answer was not located. I think I'm supposed to use an if/end or if/else kind of statement, but I'm not completely sure. I have the code listed below, any help would be greatly appreciated.
syms x
func=('x^2 - 4');
A=0; % A= x(k-1)
B=10;% B= x(k)
abs_err=0.00001;
n=5; %number of iterations
f = inline(func);
C = B - ((B-A)/(f(B) - f(A)))*f(B); % C= x(k+1)
display([' The function to be used is ' func])
fprintf(' The first guess, x(1) is equal to %g\n',A)
fprintf(' The second guess, x(2) is equal to %g\n',B)
fprintf(' The absolute approximate error, Ea, is equal to %g\n',abs_err)
fprintf(' The maximum number of iterations to conduct, n, is equal to %g\n',n)
disp(' ')
while abs(f(C)) > abs_err
A=B;
B=C;
C= B - ((B-A)/(f(B) - f(A)))*f(B);
n=n+1;
if(n==1000)
break
end
end
disp('Outputs')
display([' The root of the function = ' num2str(C)])

採用された回答

Image Analyst
Image Analyst 2013 年 11 月 18 日
編集済み: Image Analyst 2013 年 11 月 18 日
After the loop:
if n >= 1000
message = sprintf('No solution found after %d iterations.', n);
uiwait(warndlg(message));
else
message = sprintf(('Outputs\n The root of the function = %f\n', C);
uiwait(warndlg(message));
end

その他の回答 (1 件)

Chris
Chris 2013 年 11 月 18 日
Thank you very much, that helped a lot.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by