Evaluate string as structure
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I wish to load a structure based on a string input and copy the contents to a new structure. I can do this with eval, but would prefer not to.
For example:
user_string = 'structure_name';
load( user_string )
new_data = eval( user_string );
The structure 'structure_name' has several fields and is saved as a .mat file.
Using (user_string) to evaluate the structure isn't an option
0 Kommentare
Akzeptierte Antwort
Stephen23
am 1 Okt. 2019
Bearbeitet: Stephen23
am 1 Okt. 2019
N = 'structure_name';
S = load(N); % load into an output variable (a scalar structure)
new_data = S.(N);
Or, if there is exactly one variable in the .mat file:
C = struct2cell(S);
new_data = C{1};
4 Kommentare
Stephen23
am 1 Okt. 2019
Bearbeitet: Stephen23
am 1 Okt. 2019
"As I said, easily done but would be neater if it could be donw at the load stage."
Sure, it might be neat.
But it isn't possible (for the reason I explained in my previous comment).
"When I load it in to the new variable I have ..."
Which is why I showed you two methods for removing the "superfluous structure level" without awful eval. However you seem to be only looking at the first part of my code (i.e. load into a scalar structure) and not at those two methods.
"The problem isn't with your solution, but more the data I have to access."
I don't see why your data is a problem at all. The similar examples I tried worked for me.
"Whereas what I want is"
Sure, and that is exactly what my code gives you.
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!