필터 지우기
필터 지우기

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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by