Effacer les filtres
Effacer les filtres

Constructor for a class, that accepts name-value pairs for setting properties

29 vues (au cours des 30 derniers jours)
Alex Alex
Alex Alex le 17 Juin 2021
Commenté : Alex Alex le 17 Juin 2021
Hello! Could anyone advise on how to write a class constructor, that accepts name-value pairs for setting properties? For the untouched properties it must use predefined values. Using like this:
X = classX('Prop1',val1,'Prop3',val3)
Thanks

Réponse acceptée

Matt J
Matt J le 17 Juin 2021
Modifié(e) : Matt J le 17 Juin 2021
With a recent Matlab version, you can do,
classdef classX
properties
Prop1, Prop3;
end
methods
function obj=classX(namedArgs)
arguments
namedArgs.Prop1=default1;
namedArgs.Prop3=default3;
end
obj.Prop1=namedArgs.Prop1;
obj.Prop3=namedArgs.Prop3;
end
end
end
  1 commentaire
Alex Alex
Alex Alex le 17 Juin 2021
Thank you Matt, this is exactly what I asked. I tried and it works.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by