1
votes

Write a function equation(M,epsilon,tol) which sets the solution of x=M+epsilon*sin(x)

Function:

function x=newtonp(f, x, tol, h)
 
if nargin<4
   h=1e-8
end
 
if nargin<3
   tol=1e-8
end
 
while abs(f(x))>tol
   g=(f(x+h)-f(x))/h
   x=x-f(x)/g
end
end
 
function y=equation(M,epsilon,tol)
   y=M+epsilon*sin(x)-x
end

Code to call your function:

For example:

newtonp(@equation(0.5,0.5,1e-5),2,1e-5,1e-8)

Then I get Undefined function 'equation' for input arguments of type 'double'., but I don't know why. Can anyone explain it to me?

EDIT:

Using FangQ's answer I have:

function y=equation(M,epsilon,tol)
y.newtonp=@computeNewtonp
y.sin=@computeSin
end
 
function x=computeNewtonp(f,x,tol,h)
if nargin<4
h=1e-8
end
if nargin<3
tol=1e-8
end
fx=f(x)
while abs(fx)>tol
g=(f(x+h)-fx)/h
x=x-fx/g
abs(fx)
end
end
 
function z=computeSin(x,epsilon,M)
x=computeNewtonp(f,x,tol,h)
z=epsilon*sin(x)-x+M
end

However the I have: Variable y must be of data type double. It is currently of type struct. Check where the variable is assigned a value

2

2 Answers

1
votes

if you write a function inside a function unit, it is called a local function

https://www.mathworks.com/help/matlab/ref/localfunctions.html

this function is only visible to the first function, but you can make it visible by letting the main function return a handle, like in this tutorial

https://www.mathworks.com/help/matlab/matlab_prog/call-local-functions-using-function-handles.html

0
votes

I think you may need to define equation as a function of x when you would like to use it in newtonp:

function y=equation(x,M,epsilon,tol)
   y=M+epsilon*sin(x)-x;
end

newtonp(@(x) equation(x,0.5,0.5,1e-5),2,1e-5,1e-8) % use anonymous function

and you will obtain

ans =  0.88786