将匿名函数传递给方法

时间:2015-11-26 15:29:50

标签: matlab class oop global-variables anonymous-function

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)a x出错 testclass / Calculate出错(第18行)             this.F(1); test1中的错误(第3行) solver.Calculate(); *

1 个答案:

答案 0 :(得分:1)

这是与匿名函数正在使用的工作空间相关的问题。另请参阅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),至少据我所知。

相关问题