Method with struct input: how to accept different object subfields?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function-Based Unit Tests 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!