I found the solve. You can see my account on the stackoverflow.
Global variable and class
7 次查看(过去 30 天)
显示 更早的评论
testcalss.m
classdef testcalss
properties(Access = public)
a;
F;
end
methods(Access = public)
function this = testcalss()
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
test.m:
global solver;
solver = testcalss();
solver.Calculate();
I execute test and after it I get such message:
Undefined function or variable 'a'.
Error in testcalss/testcalss/@(x)a*x
Error in testcalss/Calculate (line 18)
this.F(1);
Error in test1 (line 3)
solver.Calculate();
Where is my bug?
0 个评论
采纳的回答
更多回答(1 个)
Adam
2015-11-26
The definition
this.F = eval('@(x)a * x');
has no idea what 'a' is, it has not been defined in this scope.
Using eval is a very bad idea in general, but that is a side issue other than that I have deliberately never taken the time to understand fully how it works.
this.F = eval('@(x) this.a * x');
would be syntactically fine so far as I can see, but then you try to eval the setting of a immediately afterwards. this.a would need to be set before the above call, but why do you need eval for that. Just use
this.a = 5;
followed by either
this.F = @(this,x) this.a * x
or
this.F = @(a,x) a * x
and pass in this.a as an argument when you call it, though it isn't at all obvious why you would want such a setup rather than just a standard function on your class that use the class property 'a'.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Power and Energy Systems 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!