Using the secant method for a different function

5 views (last 30 days)
Hi. I have this code for using the secant root for finding the the root of an equation. I am quite new to Matlab with little experience. I am just wondering rather than inputting my function(func = x^2 + x -1;) into the script how can I use a function from another script here? As I want to play around with the equation in another script and then not have to change this script when using different functions. I have tried removing my function from the script and inputting it into another script and then I tried f =inline(@func) but this does not work. Can someone please help me as I have hit a stump with this and I know it is probably something very simple. Thanks!
% Find the roots of using Secant Method
% func --> function is taken by user
% like sin(x) or x^2 + x - 1 or any other but use the same format
% i.e. use paranthesis as used above with 'x' for sin, cos,... etc
% and spacing between '+' or '-' operation
% a --> Xn-1
% b --> Xn
% c --> Xn+1
% maxerr --> Maximum Error in Root
syms x;
func = x^2 + x -1;
a = input('Ener Lower Limit: ');
b = input('Ener Upper Limit: ');
maxerr = input('Enter Maximum Error: ');
f = inline(func);
c = (a*f(b) - b*f(a))/(f(b) - f(a));
disp(' Xn-1 f(Xn-1) Xn f(Xn) Xn+1 f(Xn+1)'); disp([a f(a) b f(b) c f(c)]);
while abs(f(c)) > maxerr
b = a;
a = c;
c = (a*f(b) - b*f(a))/(f(b) - f(a));
disp([a f(a) b f(b) c f(c)]);
end
display(['Root is x =' num2str(c)]);

Answers (1)

Jan
Jan on 16 Mar 2013
Do you really want a symbolical solution? If not:
Either define your function in a function:
function y = func(x)
y = x^2 + x -1;
Then provide @func as input to your secant method.
Or use an anonymous function:
func = @(x) x^2 + x -1;
  2 Comments
Ben
Ben on 19 Mar 2013
Thanks for the help Jan. I am looking for the numerical solution to the root of the function. I have tried your approach however I am still getting the following error:
Error using inline (line 47) Input must be a string.
Error in secant2 (line 18)
f = inline(fun1);
And I still can't understand why this does not work?
Jan
Jan on 19 Mar 2013
Omit the inline, because it is not useful when you have a function handle already.

Sign in to comment.

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!