Newtons Method, help calling anon function inside of function file
Mostra commenti meno recenti
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)
Risposte (1)
Walter Roberson
il 17 Feb 2019
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 Commenti
Peter M Hogan
il 17 Feb 2019
Walter Roberson
il 17 Feb 2019
Your while loop assigns new values to x(k) but it does not calculate and assign new values to ex(k) so as soon as k increments then you run into difficulties.
Peter M Hogan
il 18 Feb 2019
Modificato: Peter M Hogan
il 18 Feb 2019
Walter Roberson
il 18 Feb 2019
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)
Categorie
Scopri di più su Get Started with MATLAB in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!