Can I access properties of a class object by using a variable in the call?
55 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Steven Lord
2018-3-2
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!