フィルターのクリア

Method with struct input: how to accept different object subfields?

1 回表示 (過去 30 日間)
Xh Du
Xh Du 2017 年 3 月 10 日
コメント済み: Xh Du 2017 年 3 月 13 日
Hi all,
In a method, how to accept different object subfields?
https://uk.mathworks.com/help/matlab/matlab_oop/ordinary-methods.html
Above site gives an example of addData method. Code is here:
classdef MyData
properties
Data = 0
end
methods
function obj = addData(obj,val)
newData = obj.Data + val;
obj.Data = newData;
end
end
end
My understanding is when applying addData to object, 'val' can be replaced with any variable to allow different inputs, which is good.
However, if there is another output subfield in obj, say 'Data1', this method cannot be reused to 'Data1', as it will only recognize 'Data' as the subfield here.
Of course I can write a new method:
function obj = addData1(obj,val)
newData = obj.Data1 + val;
obj.Data1 = newData;
end
such that Data1 can also be accepted, but this is cumbersome as the operation is repeated. What is the correct way to allow different struct function output here?
Thank you!
  1 件のコメント
Stephen23
Stephen23 2017 年 3 月 10 日
編集済み: Stephen23 2017 年 3 月 10 日
Numbering variables is a bad design decision which makes code more complicated, slower, and buggier:

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

採用された回答

Guillaume
Guillaume 2017 年 3 月 10 日
編集済み: Guillaume 2017 年 3 月 10 日
I'm not sure I understand fully what you're asking, particularly as you're not using correct terms. There are no structures, fields or subfields in any of the code you've shown (and I've no idea what you mean by output subfield). An object has properties (and methods, and optionally events).
The properties of an objects are defined in the classdef block. While there is a way to have dynamic properties in matlab it's a fairly advanced form of programming which I wouldn't recommend. For the common case the properties are set by the class and the user of the class cannot create more properties.
Also note that in the example you've shown the addData method is not particularly useful since the property is public (i.e. can be modified by users of the class). You could simply bypass it and do:
o = myData; %instantiate object
o.Data = o.Data + val; %modify Data directly without calling addData
I'm not sure what it is you're trying to do. What is your ultimate goal?
  10 件のコメント
Guillaume
Guillaume 2017 年 3 月 10 日
Yes, slight bug, but you get the idea. Note that in real code, I wouldn't use char arrays as toggles, I would either pass the numeric index of the row directly or use categoricals.
Xh Du
Xh Du 2017 年 3 月 13 日
Many thanks to you all!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFunction-Based Unit Tests についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by