Using the secant method for a different function
5 ビュー (過去 30 日間)
古いコメントを表示
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)]);
0 件のコメント
回答 (1 件)
Jan
2013 年 3 月 16 日
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 件のコメント
Jan
2013 年 3 月 19 日
Omit the inline, because it is not useful when you have a function handle already.
参考
カテゴリ
Help Center および File Exchange で Function Creation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!