Can I access properties of a class object by using a variable in the call?

83 views (last 30 days)
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

Accepted Answer

Steven Lord
Steven Lord on 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

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!