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
Walter Roberson
2016년 4월 21일
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)
Diego Soler Polo
2016년 4월 21일
Walter Roberson
2016년 4월 21일
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
Steven Lord
2016년 4월 21일
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.]
Diego Soler Polo
2016년 4월 22일
답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!