Renaming the fields of structure

144 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2022-11-2
编辑:Stephen23 2022-11-2
"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.

请先登录,再进行评论。

回答(2 个)

Walter Roberson
Walter Roberson 2022-11-2
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 2022-11-2
编辑:Bruno Luong 2022-11-2
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 个评论
sai prasanna sai prasanna m s
Shouldn't I use a save method so the changes reflect in original data ?
Bruno Luong
Bruno Luong 2022-11-2
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by