Define shared subfunctions inside a classdef *.m file?

2 ビュー (過去 30 日間)
Knut
Knut 2011 年 2 月 21 日
I want to define a relatively small class (small enough that it makes sense to do everything inside of one file). I want to reuse a common subfunction between several methods, and having this subfunction inside of the classdef would make it cleaner, easily portable and automatically private. However, I have not been able to do so. Is there any way to accomplish it?
>> d = dummy;
>>??? Undefined function or variable 'my_pi'.
>>
>>Error in ==> dummy>dummy.dummy at 10
>> obj.dummy = my_pi();
dummy.m:
classdef dummy
properties
value;
end
methods
function y = my_pi()
y = 3.141592;
end
function obj = dummy()
obj.dummy = my_pi();
end
end
end

採用された回答

per isakson
per isakson 2011 年 2 月 21 日
You can define subfunctions in the same file after the definition of the class, ie
classdef dummy
...
...
end % classdef
function out = subfun1( in )
...
end
/ per

その他の回答 (1 件)

David Young
David Young 2011 年 2 月 21 日
Non-static methods require an object as the first argument, and as my_pi is not declared static and doesn't have an argument, it isn't found.
Rather than putting my_pi at the end of the file, I would include it properly in the class by declaring it to be static:
classdef dummy
properties
value;
end
methods
function obj = dummy()
obj.value = dummy.my_pi();
end
end
methods (Static)
function y = my_pi()
y = 3.141592;
end
end
end
You need to use the class name in the call to the static method. I've also corrected the assignment in the constructor: I assume that you intented to set the value property.
You could also set my_pi's access to private if you want it only to be visible from other methods of the class.
  8 件のコメント
David Young
David Young 2011 年 2 月 22 日
Agreed - it does depend on the programming context. Also, I see I can't count. Oh well...
Knut
Knut 2011 年 2 月 23 日
@David:
Yes, I accepted the first reply before I saw yours, because it did solve my problem, your post just solved it more elegantly (for me). Now, I cant seem to change the acceptance.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by