How to access object loaded into a struct when object variable name (as saved) is unknown
Mostrar comentarios más antiguos
I have a user-defined class type named classAvengerTrack. The purpose of this is to be a container for radar data on a specific track, so you can imagine that you might have many intances of this class to describe all the tracks in a given radar data set, and that naturally each instance would have a different variable name, such as 'track543'
One of the properties in classAvengerTrack is a table of position reports, with columns such as timestamp, latitude, longitude, etc. So if I wanted to access that table of position reports for a specific track I would use:
track543.positionReports
Simple enough so far.
I want the user to be able to save as specific instance of this object to a .mat file. I want to be able to load that .mat file in another function and act on that postionsReport table. The trouble is, I won't necessarily know the original variable name. For example:
userSavedObject = 'airTrack.mat'
track = load (userSavedObject);
Will load the object into a struct. If I knew that the user saved an instance of the classAvengerTrack object named 'track543' then getting to the positionReports table would be as easy as:
track.track543.positionReports
However, the function loading the .mat file has no prior knowledge of this file, only that it is expected to be an object of type classAvengerTrack.
Question: How do I reference a property of an object that is trapped in struct?
I have tried every variation of indexing I can think of. I either get an error, or I get this:
K>> results(1).positionReports
Reference to non-existent field 'positionReports'.
K>> results(1)
ans =
struct with fields:
ft1AirTruth_Avenger: [1×1 classAvengerTrack]
Any help you can provide to restore my sanity is greatly appreciated. I'm using version R2017a.
2 comentarios
"...naturally each instance would have a different variable name, such as 'track543'"
That isn't "natural" at all, it is bad data design.
Meta-data (such as track IDs) is data, and forcing data into variable names makes accessing variables slow, complex, and buggy. Your code and processing would be much simpler if the variable names did not change and the meta-data was simply saved inside a variable as data (which meta-data is), rather than being forced into variable names:
If the original data and meta-data was simply stored as something like:
positionReports = ...
trackNumber = 543;
save(...,'positionReports','trackNumber')
then you would not have needed to ask this question in the first place.
Roger Pierson
el 8 de Dic. de 2019
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Multi-Object Trackers en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!