Passing functions to functions
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hi, i am trying to write a code for Newton's Method, but before I can even get to where I am actually doing the method i can't get the function and its derivative to be defined They're both supposed to be user-inputted, in a single variable in the function call, where we call another function to define it exactly as [fx dfx]=f(x)
Here are the specific instructions regarding what I am confused about
f: a function handle; [fx,dfx]=f(x) must compute f(x) (fx) and f(x) (dfx).
but I don't under stand, nor can i get it to work. I've been passing the function 'myfunc' into Newton, and I've tried many different things, none work. myfunc.m
function [fx dfx] = myfunc(x)
fx=cos(x) -x;
dfx=-sin(x)-1;
end
and Newton.m
function x= Newton(f,x0,pflag,Tol,ftol,maxit)
xold=x0
x=xold
[fx dfx]=f(x)
err= x0;
ferr= abs(f(xold));
maxit=0;
while err>tol && ferr>tol
xnew=xold-fx(xold)/dfx(xold);
err=xnew-xold;
ferr=abs(fx(xnew));
maxit=maxit+1;
end
0 comentarios
Respuestas (1)
Stephen23
el 10 de Oct. de 2015
Editada: Stephen23
el 10 de Oct. de 2015
Your basic problem is that you are not calling f inside the while-loop: you call f twice before the loop, but never inside the while loop. Because of this the fx and dfx values never change during the loop iterations. You need to reconsider your basic algorithm: it is a good idea to draw any algorithm on paper first, so that you have clear understanding of how it works.
Also make sure that you are calling Newton with the function handle for your custom function::
x = Newton(@myfunc,...
Note that myfunc must be a local function to Newton, OR in its own separate M-file (it appears that you are using the second option, which is fine).
2 comentarios
Stephen23
el 12 de Oct. de 2015
Editada: Stephen23
el 12 de Oct. de 2015
I did not write that you need to remove the call to f before the loop, only that you need to add a call to f inside the loop. The first call to f (before the loop) gives your initial values, each call after that (inside the loop) gives the newest estimated values.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!