Reference instances of class object

3 views (last 30 days)
Kelly Shelts
Kelly Shelts on 15 Mar 2021
Answered: Asvin Kumar on 19 Mar 2021
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.

Answers (1)

Asvin Kumar
Asvin Kumar on 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);


Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by