将匿名函数传递给方法

Passing anonymous function to method

testcalss.m:

classdef testclass
    properties(Access = public)
        a;
        F;
    end
    methods(Access = public)
        function this = testclass()            
            if (1 == 1)
                this.F = eval('@(x)a * x');
                eval('this.a = 5');
            end
        end
        function Calculate(this)
            a = this.a;
            this.F(1);
        end
    end
end

test1.m:

global solver;
solver = testclass();
solver.Calculate();

我执行测试,然后收到这样的消息:

未定义函数或变量'a'。 testclass/testclass/@(x)ax 出错 testclass/Calculate 中的错误(第 18 行) this.F(1); test1 错误(第 3 行) solver.Calculate();*

这是一个与匿名函数使用的工作区相关的问题。另请参阅 here。这应该有效:

 classdef testclass
    properties(Access = public)
        a;
        F;
    end
    methods(Access = public)
        function this = testclass()            
            if (1 == 1)
                this.F = '@(x)a * x';
                this.a = 5;
            end
        end
        function Calculate(this)
            a = this.a;
            f = eval(this.F);
            f(1)
        end
    end
end

本质上,您是在本地使用 eval 创建一个新的匿名函数,因为您不能像这样传递带有固定参数(如 a)的匿名函数,至少据我所知是这样。