【问题标题】:Having trouble evaluating an anonymous function using feval on Matlab在 Matlab 上使用 feval 评估匿名函数时遇到问题
【发布时间】:2020-09-10 15:54:17
【问题描述】:

我正在为二分法编写自己的 Matlab 代码,并定义了一个匿名函数,我正在尝试为其查找根。它会生成一个简单的图表,我知道如果它运行正常,它可以很容易地找到根。

当我的代码开始以给定的 x 值评估函数时,它会返回:

Error using feval
Function to evaluate must be represented as a string scalar, character vector, or
function_handle object.

Error in bisection (line 3)
fa = feval(f, a);

我的完整代码是:

function m=bisection(f,a,b,imax,tol)

    fa = feval(f, a);
    fb = feval(f, b);
    i=0;

    if fa*fb>0
        disp('No root here: pick a new interval')
        return
    end
    while abs(b-a) >= tol
        i = i + 1;
        m=(a+b)/2;
        fm = feval(f, m);
        if fa*fb<0
            b = m;
        else
            a = m;
        end
        abs(fm);
    end
    % Show the last approximation considering the tolerance
    w = feval(f, m);
    fprintf('\n x = %f produces f(x) = %f \n %i iterations\n', m, fm, i-1);
    fprintf(' Approximation with tolerance = %f \n', tol);
end

我的功能是:

function [T] = freezing(x)

alpha = 0.138*10^-6;
Ti = 20;
Ts = -15;
t = 60*60*24*60;
tol = 10^-13;

%x = linspace(0,3);

T = @(x) (Ti-Ts)*erf(x./(2*sqrt(alpha*t)))+Ts;
dT = @(x) (Ti-Ts)*(1/sqrt(pi*alpha*t))*exp(-x.^2./(4*alpha*t));
T = T(x);
end

我真的不确定问题出在哪里 - 在我的命令窗口中,我可以轻松输入 x 值并获得输出。任何建议都非常感谢!

【问题讨论】:

  • 这能回答你的问题吗? What is a function handle and how is it useful?
  • 我在二等分中将 freeze(x) 传递给 f。当我评估冻结(#)时,它在命令窗口中运行良好。 a 和 b 已在您发送给我的示例中进行了预定义,因此我仍然不确定解决方案是什么。
  • 就是这样!!谢谢普拉纳夫!如果您将其发布为解决方案,我会将其标记为已解决。 :-)

标签: matlab anonymous-function


【解决方案1】:

feval 需要 f 成为 function handle。当您调用bisection 时,我怀疑您将freezing 的结果传递给bisection,而不是将函数句柄传递给freezing

您需要使用bisection(@freezing, ...) 而不是bisection(freezing(...), ...)

@freezing 创建了一个传递给二分法的函数句柄。执行后者会将冻结的结果传递给bisection。

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    相关资源
    最近更新 更多