MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

Asked by Chris
on 18 Nov 2013

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)])

*No products are associated with this question.*

Answer by Image Analyst
on 18 Nov 2013

Edited by Image Analyst
on 18 Nov 2013

Accepted answer

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

## 0 Comments