Passing functions to functions

조회 수: 1 (최근 30일)
Travis Melka
Travis Melka 2015년 10월 10일
편집: Stephen23 2015년 10월 12일
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

답변 (1개)

Stephen23
Stephen23 2015년 10월 10일
편집: Stephen23 2015년 10월 10일
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
Travis Melka
Travis Melka 2015년 10월 11일
fx and dfx never end up getting defined in the first time, i get an error. Therefore I haven't even gotten to the while loop.
Stephen23
Stephen23 2015년 10월 12일
편집: Stephen23 2015년 10월 12일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by