Renaming the fields of structure

141 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 2 Nov 2022
Edited: Stephen23 on 2 Nov 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.
sai prasanna sai prasanna m s
That makes lot of sense. Thanks for your elaborate answer. I shall recheck if I need to do this exercise at all.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 2 Nov 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.

Bruno Luong
Bruno Luong on 2 Nov 2022
Edited: Bruno Luong on 2 Nov 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 Comments
sai prasanna sai prasanna m s
Shouldn't I use a save method so the changes reflect in original data ?
Bruno Luong
Bruno Luong on 2 Nov 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.

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!