How do I rename variables from workspace for multiple matfiles?

14 ビュー (過去 30 日間)
KuanTing Wu
KuanTing Wu 2022 年 3 月 24 日
コメント済み: Rik 2023 年 7 月 12 日
Hello there! I am trying renaming those variables, e.g., 'img' to 'img_ldct' and 'lab' to 'lab_ldct', and making these two matfiles' variable names become same.
img_ldct=img;
clear('img')
I have tried the above code and it worked, but the new variable name did not saved in matfiles,which meant when I clicked the workspace later, the variable name was still 'img', not 'img_ldct'. How can I change variable names correctly? Also, is it possible to rename multiple matfiles automatically with the same name-changing rule, e.g., adding '_ldct' after original variable names?
Please suggest and thank you for helping!

採用された回答

Les Beckham
Les Beckham 2022 年 3 月 24 日
clearvars
load('filename.mat') % load data that you want to change (replace filename with actual name of your file)
img_ldct=img; % do the rename
clear('img')
save('matfile1.mat') % save the result with the change
% repeat for any other mat files that you want to make changes to
  1 件のコメント
KuanTing Wu
KuanTing Wu 2022 年 3 月 25 日
Thank you! I really appreciate your suggestion and it works! May I ask how should I use a loop to rename multiple matfiles automatically with the same name-changing rule, e.g., adding '_ldct' after original variable names?

サインインしてコメントする。

その他の回答 (1 件)

Rik
Rik 2022 年 3 月 25 日
編集済み: Rik 2023 年 7 月 12 日
With the syntax Les posted it is not possible to apply this to multiple mat files and variables automatically, which is one of the reasons to load to a struct instead. That way it is obvious where variables are coming from and you can use fieldnames to get all the variable names.
rename_variables('filename.mat','_ldct')
function rename_variables(filename,suffix)
Sin=load(filename);
Sout=struct;
fn=fieldnames(Sin);
for n=1:numel(fn)
Sout.([fn{n} suffix])=Sin.(fn{n});
end
save(filename,'-struct','Sout')
end
I will leave it as an excersize to you to write comments and documentation for this function.
  4 件のコメント
Belén
Belén 2023 年 7 月 11 日
There seems to be a typo, it should be:
fn=fieldnames(Sin);
Rik
Rik 2023 年 7 月 12 日
Thank you for catching this. I have edited my answer.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by