How to create an object using class name

53 vues (au cours des 30 derniers jours)
Sylvain
Sylvain le 18 Fév 2020
Commenté : Sylvain le 21 Fév 2020
In my function, I am getting the class name from an object to create a new one. What is the right syntax to creat the new Object ?
function newObj = createNewObject(obj)
className = class(obj);
newObj = className();
end

Réponse acceptée

Matt J
Matt J le 18 Fév 2020
function newObj = createNewObject(obj)
newObj = feval( class(obj) );
end
  3 commentaires
Matt J
Matt J le 20 Fév 2020
Sylvain
Sylvain le 21 Fév 2020
Thank you, very instructive

Connectez-vous pour commenter.

Plus de réponses (2)

Sky Sartorius
Sky Sartorius le 18 Fév 2020
A quick and dirty approach that will work in many cases is to use eval:
function new = createNewObjectOfThisClass(original)
new = eval([class(original) '.empty;']);
end

Image Analyst
Image Analyst le 18 Fév 2020
That won't work for all types of objects, like structures, other custom-designed classes, etc. I think your best bet is to just make a copy of the variable
function newObj = createNewObject(obj)
newObj = obj;
end
It will have the values of the input object, but more importantly, it will inherit all the fields, properties, and methods of your input class. As you can see you actually don't even need this function at all since it's just a wrapper than essentially does nothing. You could just simply do this
newObj = obj;
rather than this
newObj = createNewObject(obj)
  1 commentaire
Matt J
Matt J le 18 Fév 2020
Modifié(e) : Matt J le 18 Fév 2020
I disagree. It's often necessary to call the constructor to instantiate a new, independent version of the original object. For example, if obj is an object of a handle class then
newObj = obj
does not give you an indepedent copy of obj. Just another handle to its property data.

Connectez-vous pour commenter.

Catégories

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by