How to robustly set class object properties in the class constructor when using name-value approach without handling them one-by-one?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Diaa
am 15 Jul. 2022
Beantwortet: Jeff Miller
am 16 Jul. 2022
For the following, is there any robust way to set the class object properties at once by copying each input struct field value to its corresponding class object property wihtout iterating over them one-by-one?
classdef classX
properties
Prop1, Prop2, Prop3;
end
methods
function obj = classX(namedArgs)
arguments
namedArgs.Prop1 = default1;
namedArgs.Prop2 = default2;
namedArgs.Prop3 = default3;
end
% How to make the following lines robust and indepedent of the number of object properties?
obj.Prop1=namedArgs.Prop1;
obj.Prop2=namedArgs.Prop2;
obj.Prop3=namedArgs.Prop3;
end
end
end
0 Kommentare
Akzeptierte Antwort
Jeff Miller
am 16 Jul. 2022
One option might be something like this:
% How to make...
fnames = fieldnames(namedArgs);
for ifield=1:length(fnames)
s = fnames{ifield};
obj.(s) = namedArgs.(s);
end
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!