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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by