1

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

Community
  • 1
  • 1
Liam153
  • 11
  • 3

2 Answers2

1

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

FangQ
  • 1,444
  • 10
  • 18
  • Could you explain to me how it would look in my task? I was trying in this way: function y=equation 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 but then I also get the same statement – Liam153 Apr 08 '20 at 00:49
  • your function is simple enough to write as an inline function, like `myfun=@(x,M,epsilon) y=M+epsilon*sin(x)-x;` Then you can pass it to your function as a function handle. ` – FangQ Apr 08 '20 at 01:51
  • No, because in this task I MUST use function like newtonp to calculate x and then I have equation(M,epsilon,tol), where tol is an approximation error. So I can't skip function newtonp and write that I have equation (x,M,epsilon) – Liam153 Apr 08 '20 at 06:10
0

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81