【问题标题】:Undefined function 'equation' for input arguments of type 'double''double' 类型的输入参数的未定义函数 'equation'
【发布时间】:2020-07-20 07:03:35
【问题描述】:

写一个函数方程(M,epsilon,tol) 设置x=M+epsilon*sin(x)的解

功能:

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

调用函数的代码:

例如:

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

然后我得到未定义函数“方程式”,用于类型为“双”的输入参数。,但我不知道为什么。谁能给我解释一下?

编辑:

使用 FangQ 的答案我有:

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

但是我有:变量 y 必须是双精度数据类型。它目前是结构类型。检查变量的赋值位置

【问题讨论】:

    标签: matlab function octave newtons-method


    【解决方案1】:

    如果你在一个函数单元内写一个函数,它被称为局部函数

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

    这个函数只对第一个函数可见,但是你可以通过让主函数返回一个句柄来使它可见,就像在本教程中一样

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

    【讨论】:

    • 您能向我解释一下它在我的任务中的样子吗?我是这样尝试的: function y=equation y.newtonp=@computeNewtonp y.sin=@computeSin end function x=computeNewtonp(f,x,tol,h) if nargintol g=(f(x+h)-fx)/hx=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 但我也得到相同的语句
    • 你的函数很简单,可以写成内联函数,比如myfun=@(x,M,epsilon) y=M+epsilon*sin(x)-x; 然后你可以把它作为函数句柄传递给你的函数。 `
    • 不,因为在这个任务中我必须使用像 newtonp 这样的函数来计算 x,然后我有方程(M,epsilon,tol),其中 tol 是一个近似误差。所以我不能跳过函数 newtonp 并写出我有方程 (x,M,epsilon)
    【解决方案2】:

    当您想在newtonp 中使用它时,我认为您可能需要将equation 定义为x 的函数:

    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
    

    你会得到

    ans =  0.88786
    

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多