Method with struct input: how to accept different object subfields?
显示 更早的评论
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 个评论
Numbering variables is a bad design decision which makes code more complicated, slower, and buggier:
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Tables 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!