Can I access properties of a class object by using a variable in the call?
52 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Kevin Snyder
le 2 Mar 2018
Commenté : Kevin Snyder
le 2 Mar 2018
Relatively new to MATLAB, so sorry in advance.
I have a class object that I would like to change with the use of a variable. The function is a template of sorts that produces various plots for a growing number of sensors. The use of the variable is purely to make it very apparent to others which variables to change, and ensures that all the instances get changed, this works well for other values but not for class properties.
function[] = somefunc(input)
%Only change this variable Jake
VAR=nameOfProperty
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if(someObject(1,1).VAR==input)
plot(someObject(1,1).x,someObject(1,1).y);
end
%%%%%lots of other code goes here%%%%
end
Can someone tell me if there is a better way to go about this? or point me in the right direction? My search queries have not been very helpful
0 commentaires
Réponse acceptée
Steven Lord
le 2 Mar 2018
So let me make sure I understand what you're trying to do. You have an object that is an instance of a class and a variable that contains the name of a property of that object. You want to use the variable containing the name to access the property of the object?
If that's the case, you can use the same technique you would use to access a field of a struct array using a variable containing a field name to access a property of an object. For example, the graph class has a property named Edges.
G = graph(bucky);
You can either access the Edges property by hard-coding it in your program:
N1 = G.Edges;
or using a variable containing the name Edges.
propertyName = 'Edges';
N2 = G.(propertyName);
The variables N1 and N2 are the same.
isequal(N1, N2) % returns true
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!