【问题标题】:Passing anonymous function to method将匿名函数传递给方法
【发布时间】:2015-11-26 15:29:50
【问题描述】:

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 中的错误 测试类/计算错误(第 18 行) 这个.F(1); test1 中的错误(第 3 行) 求解器.Calculate();*

【问题讨论】:

  • 你写过构造函数吗?您确定 this 语法在 MATLAB 上有效吗?
  • 是的,这个语法有效。有一个构造函数。你可以这样做:global solver; a = solver.a; b = solver.b; c = solver.c。在它之前,当我创建我的类时,我写了一行global solver; solver = Parabolic();。
  • 你能把它编辑成你的问题吗?而且,可以提供一些可运行的东西吗?
  • @lhcgeneva 我修复了我的帖子。请再看一遍

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


【解决方案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)的匿名函数,至少据我所知。

【讨论】:

    猜你喜欢
    • 2012-12-24
    • 2012-11-24
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2015-01-09
    • 2015-01-07
    • 2015-05-09
    相关资源
    最近更新 更多