Global variable and class

7 ビュー (過去 30 日間)
hedgehogues
hedgehogues 2015 年 11 月 26 日
回答済み: hedgehogues 2015 年 11 月 26 日
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?

採用された回答

hedgehogues
hedgehogues 2015 年 11 月 26 日
I found the solve. You can see my account on the stackoverflow.

その他の回答 (1 件)

Adam
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'.

カテゴリ

Help Center および File ExchangePower and Energy Systems についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by