Use a string as a struct name

208 views (last 30 days)
Ulrik William Nash
Ulrik William Nash on 10 Nov 2019
Answered: Walter Roberson on 10 Nov 2019
In different files, I have a struct. Each struct has the same underlying structure and variable names. But the name of each struct is different, yet predicable by the filename
I want to programatically load the files (no problem), create a string from information in the filename (no problem), and then use this string as the structname. For example (getting data in the matrix 'age'):
filename = 'output_setting1.mat'
structname = 'setting1'
data = setting1.age
How can I convert structname = 'setting1' so I can use it as shown in the last line?

Answers (1)

Walter Roberson
Walter Roberson on 10 Nov 2019
filename = 'output_setting1.mat';
file_struct = load(filename);
fn = fieldnames(file_struct);
data_struct = file_struct.(fn{1});
data = data_struct.age;
No need to dynamically create the name of a variable: you can create the name of a field instead.

Community Treasure Hunt

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

Start Hunting!

Translated by