Renaming the fields of structure
147 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
sai prasanna sai prasanna m s
el 2 de Nov. de 2022
Comentada: sai prasanna sai prasanna m s
el 2 de Nov. de 2022
I have a set of .mat files.
file1.mat is a struct with field 'data'
file2.mat is a struct with field 'data'
...
filen.mat is a struct with field 'data'
How to rename fields named 'data' in all the .mat files with respective filenames.
I want the format as
file1.mat is a struct with field 'file1'
file2.mat is a struct with field 'file2'
...
filen.mat is a struct with field 'filen'
Thanks
2 comentarios
Stephen23
el 2 de Nov. de 2022
Editada: Stephen23
el 2 de Nov. de 2022
"How to rename fields named 'data' in all the .mat files with respective filenames... file1.mat is a struct with field 'file1', file2.mat is a struct with field 'file2' ... filen.mat is a struct with field 'filen' "
I strongly recommend not doing that.
Processing data in multiple .MAT files is simpler and much more robust when the variable names in each .MAT file are exactly the same (just as your current files are). In contrast, adding meta-data into variable names (such as file numbers) is one way that beginners force themselves into writing slow, complex, inefficient, obfuscated code that is buggy and hard to debug:
Even if you LOAD into an output variable, then your new variable names will be more complex and slower to process than if you simply used the existing consistent fieldname "data".
If you need to store the meta-data (i.e. filename) in the .MAT files, then the best approach is to simply add it as a new variable into each .MAT file (which you can do very easily using the -APPEND option).
It is possible that you incorrectly believe that you need to give all of those variables different names in order to LOAD them into the workspace and prevent them from overwriting in a loop... but as you did not give much context in your question, this is just a guess.
Respuestas (2)
Walter Roberson
el 2 de Nov. de 2022
I suggest using struct2cell() followed by cell2struct() (with the new field names)
This always feels like "cheating" to me, but it works pretty effectively.
0 comentarios
Bruno Luong
el 2 de Nov. de 2022
Editada: Bruno Luong
el 2 de Nov. de 2022
for i = 1:10 % 1:n
filename = sprintf('file%d', i);
s = load([filename '.mat']);
fieldname = filename;
s.(fieldname) = s.data;
s = rmfield(s,'data')
end
2 comentarios
Bruno Luong
el 2 de Nov. de 2022
Up to you. It depends if you want to perform my code once then not bother with it anymore (correct the structure saved with not desired fieldnae), or do do it everytime you read the file.
Ver también
Categorías
Más información sobre Structures 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!