Use a string as a struct name
120 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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?
0 comentarios
Respuestas (1)
Walter Roberson
el 10 de Nov. de 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.
2 comentarios
Richard Mustakos
el 17 de Mayo de 2024
Editada: James Tursa
el 17 de Mayo de 2024
It turns out there is a good reason.
I have a file with a corrupted field. I can select the file in the file browser and see a list of all the contents. I can idividually select the fields and load them, except for the corrupted field.
So, for me, this is a fall back case to load all the fields except the corrupted ones, with the names from the files.
There are two ways I can handle this:
Use 'whos' to get the fields and walk through them inside a try-catch, if it works I add the name to a list of readable fields and then struct = load(filename,fields), which requires me tto load each field twice.
Use 'whos' to get the fields and walk through them inside a try-catch, adding it to the struct as a field. In this case I only readfields once.
Either way, no problem with maintenance as the names are those from the file, not arbitrary.
James Tursa
el 17 de Mayo de 2024
Editada: James Tursa
el 17 de Mayo de 2024
@Richard Mustakos Is the file created by a 3rd party app and uncompressed? Can you manually edit the file and replace the corrupted fieldnames with valid ones, ensuring that the valid names are exactly the same length as the corrupted names? And then load the corrected file?
Ver también
Categorías
Más información sobre Environment and Settings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!