Reference instances of class object

12 vues (au cours des 30 derniers jours)
Kelly Shelts
Kelly Shelts le 15 Mar 2021
Hi,
I have a class definition called BNS. I have multiple instances of this class named in the following convention e.g. Run3, Run4, etc. And I have multiple properties named as Mic1, Mic2, Mic3, etc. Based on inputs to a function, I would like to access specified properties of specified objects. My attempt is as follows:
objectname = strcat('Run', string(run)');
propertynamme = strcat('Mic', string(mic));
OASPL = objectname.propertyname;
where run and mic are doubles defined earlier.
I get the error 'Unrecognized method, property, or field 'propertyname' for class 'string'.'
I'm not sure how to make matlab recognize the string as a property of an object.

Réponses (1)

Asvin Kumar
Asvin Kumar le 19 Mar 2021
It's not a good habit to name variables with respect to input/strings/numbers. Please strongly consider avoiding this pattern. Here's a really good post on why this is a bad idea: Why variables should not be named dynamically? by @Stephen Cobeldick
Consider using arrays instead. You can have a look at all available data types in the attached link and then pick the one that suits your needs. This includes Numeric Arrays, Cell Arrays, Tables and Maps. Structure arrays seem like a nice place to start.
If you're still looking to go ahead with your approach, you'll need to use the eval command as shown below.
objectname = strcat('Run', string(run)');
propertyname = strcat('Mic', string(mic));
value = strcat(objectname,'.',propertyname);
OASPL = eval(value);

Catégories

En savoir plus sur Logical 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!

Translated by