Clear Filters
Clear Filters

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

1 view (last 30 days)
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!

Accepted Answer

Guillaume
Guillaume on 10 Mar 2017
Edited: Guillaume on 10 Mar 2017
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 Comments
Guillaume
Guillaume on 10 Mar 2017
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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!