MATLAB:将类函数句柄传递给ode45()?

时间:2015-02-13 17:34:53

标签: matlab oop function-handle

我有一个使用ODE45来解决某些方程的类函数。我有另一个私有类函数,它表示ODE45需要解决的odefunction。但是,我无法弄清楚如何将类的ode函数的句柄传递给ODE45。以下是示例代码:

class ODESolver < handle

    methods (Access = public)

        function obj = RunODE(obj, t, y0)
            [~, Z] = ode45(@ODEFunction, t, y0);
        end

    end

    methods (Access = private)

        function dy = ODEFunction(t,y)
            % Calculate dy here.
        end

    end

end

当我运行此操作时,我收到错误消息:

Undefined function 'ODEFunction' for input arguments of type 'double'.

如果我将ODEFunction移到类之外并将其放在自己的* .m文件中,则代码运行正常。我也尝试在ode45调用中使用“@ obj.ODEFunction”,但随后它说:

Too many input arguments.

将ODEFunction保留在我的类中并且仍能将其句柄传递给ode45的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

您的私有ODEFunction不是静态方法,因此您应该写:

classdef ODESolver < handle

    methods (Access = public)

        function obj = RunODE(obj, t, y0)
            [~, Z] = ode45(@(tt, yy)obj.ODEFunction(tt, yy), t, y0);
        end

    end

    methods (Access = private)

        function dy = ODEFunction(obj, t,y)
            dy = 0.1; % Calculate dy here.
        end

    end

end

注意:您还忘记将obj作为私人ODEFunction的第一个参数传递...我正在使用静态方法编写示例,并在测试后将其粘贴到此处。

修改

如果您打算在班级中使用私人静态ODEFunction,那么您应该如何编写内容:

classdef ODESolver < handle

    methods (Access = public)

        function obj = RunODE(obj, t, y0)
            [~, Z] = ode45(@(tt, yy)ODESolver.ODEFunction(tt, yy), t, y0);
        end

    end

    methods (Static, Access = private)

        function dy = ODEFunction(t,y)
            dy = 0.1; % Calculate dy here.
        end

    end

end