problem with passing a function handle to a function

I have a code to implement Newton-Rapshon algorithm fo find the zeroes of a function. In order to try it, I defined in the terminal:
f=@(x)x^2-1
df=@(x)2*x
And then I call my function in the terminal like this: Newton1(f,df,10^-7,10,3). It should work just fine.... but instead it gives the error message: * "??? Undefined function or method 'Newton1' for input arguments of type 'function_handle'."*
I have no idea what's going wrong! Any help will be appreciated :-) The code I am using is as follows:
function [root] = Newton1(f,df,tolerance,Iterations,x0)
epsilon = 10^(-14); %Don't want to divide by a number smaller than this
%Iterations; %Don't allow the iterations to continue indefinitely
haveWeFoundSolution = false; %Have not converged to a solution yet
for i = 1 : Iterations
y = f(x0);
yprime = df(x0);
if abs(yprime) < epsilon %Don't want to divide by too small of a number
% denominator is too small
break %Leave the loop
end
x1 = x0 - y/yprime; %Do Newton's computation
if abs(x1 - x0) <= tolerance * abs(x1) %If the result is within the desired tolerance
haveWeFoundSolution = true;
break; %Done, so leave the loop
end
x0 = x1; %Update x0 to start the process again
end
if haveWeFoundSolution
root=x0;
%Sol=printf('%s is a root of the equation',x0);
disp(root)
else
display('The process did not converge')
end

5 Commenti

Make sure that code starting from "function" is stored in Newton1.m in a directory that is on your MATLAB path. File names are case sensitive for this purpose. Watch out for mistaking the '1' (one) and 'l' (lower-case L)
Thank you so much for your help, Robert. Actually, I just found out that I wasn't on the right directory. The trouble is, I don't seem to be able to change directories easily enough.... I couldn't even check in which directory I was in! I had to create the typical silly "hello world" script and save it in the same directory as my Newton1 file, make it run and wait for MatLab to ask me if I wanted to change to the directory where that silly script was. Afterwards, I ran the Newton1 function and it worked just fine.... Nonetheless, I have yet to find a less awkward way to change directories...!
pwd or cd to find out which directory you are in now. cd to change directories to a specific directory. Or give the command
filebrowser
Or if you are using release R2010b or later and have the file open in the MATLAB Editor, right-click on the tab with its name and select the option to change directory to the folder containing that file. [This generally won't work for files whose names are "Untitled" followed by 0 or more numbers, as that naming convention usually indicates the file hasn't been saved yet.]
Thanks for the help :-)

Accedi per commentare.

Risposte (0)

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by