1

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();

I execute test and after it I get such message:

Undefined function or variable 'a'. Error in testclass/testclass/@(x)ax Error in testclass/Calculate (line 18) this.F(1); Error in test1 (line 3) solver.Calculate();*

lhcgeneva
  • 1,981
  • 2
  • 21
  • 29
hedgehogues
  • 217
  • 3
  • 21

1 Answers1

1

This is a problem related to the workspace the anonymous function is using. Also refer to here. This should work:

 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

Essentially you locally make a new anonymous function using eval, because you can't pass anonymous functions with fix parameters (like a) around like this, at least as far as I am aware of.

Community
  • 1
  • 1
lhcgeneva
  • 1,981
  • 2
  • 21
  • 29