Newtons Method, help calling anon function inside of function file
2 ビュー (過去 30 日間)
古いコメントを表示
Ok so I have been tasked with writing a file myNewton which finds the root of any function given the listed inputs. I am maybe misunderstanding how to implement the method in general, but my matlab related question pertains more to the nature of calling anony functions inside of function files. I do not do this here but I anticipate that the best way to solve this problem is to do that. I am basically confused! Any help is appreciated, here is what I have so far.
function p = myNewton(f,fprime,x0,tol)
%input f, anonymous function for root finding problem
%input fprime, anonlymous function, the derivative of f
%input x0, an initial guess
%input tol, a tolerance (method will stop when successive iterates are within tol of each other)
%output p, a root f(p) = 0
x(1) = x0 - (f(x0)/fprime(x0));
k = 2;
ex(1) = abs(x(1)-x0);%error
while (ex(k-1) >= tol) %while my error is greater than tolerance
x(k) = x(k-1) - (f(x(k-1))/fprime(x(k-1)));
k = k+1;
end
end
code to call function;
%As a test, the root of f(x) = x+2^x is -0.64118574
% define f, fprime, an initial guess (you can use 1), and use a tolderance of 1e-6
% send these into the function and store the result as the variable p
format long % to display more digits
x0=1;
tol=1e-6;
myNewton('x+2^x','diff(x+2^x)',x0,tol)
0 件のコメント
回答 (1 件)
Walter Roberson
2019 年 2 月 17 日
You are calling the anonymous function properly in your code.
Your problem is that you are not passing in an anonymous function. You are passing in character vectors.
myNewton(@(x) x+2^x, @(x) 2^x * log(2) + 1, x0, tol)
You cannot ask to diff(x+2^x) unless you have the symbolic toolbox.
4 件のコメント
Walter Roberson
2019 年 2 月 18 日
Where do you assign ex(2) ?
When k = 2 you use ex(k-1) which is ex(1), which you have assigned to specifically, so that part is good. You then increment k from 2 to 3, and assign to ex(3). Your while loop then tests ex(3-1) which is ex(2) but you did not assign to ex(2)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!