how to save workspace variables with the same name they have in work space

5 ビュー (過去 30 日間)
matar hedi
matar hedi 2022 年 4 月 11 日
編集済み: Stephen23 2022 年 4 月 14 日
i have lots of variables in the workspace and want to save those with the prefix "PSD", also I want them to have the same name they have now or even better without the "PSD" prefix.
i tried to use:
vars = work PSD*

回答 (2 件)

mark li
mark li 2022 年 4 月 14 日
Hello! There is a simple demo.
%%
%test data
clear;
PSD_a = 1;
PSD_b = 2;
PSD_c =2;
a = 1;
%%
str_set = [];
Save_name = '''a.mat'''; %the save file name
Var_name = who('PSD*');
for index = 1 : length(Var_name)
str = Var_name{index};
str_new = str(5:end); %the Value 5 may be changed properly
eval([str_new '=' str ';'])
str_set = [ str_set ',' '''' str_new ''''];
end
eval([ 'save(' Save_name str_set ')'])
%%
%clear data
clear_var = ['clear(''' str_set(3:end-1) ''')' ];
eval(clear_var)

Stephen23
Stephen23 2022 年 4 月 14 日
編集済み: Stephen23 2022 年 4 月 14 日
A much simpler approach ist use SAVE's regular expression syntax:
save('mydata.mat', '-regexp','^PSD')
There is no point in making your code more complex than that.
Renaming would be best done by LOADing and changing the fieldnames, for example:
S = load('mydata.mat')
and then use dynamic fieldnames and RMFIELD.
Note that filtering variables by their names implies that you have forced meta-data into the variable names, which is generally very poor data design which will make acessing and processing your data slow, complex, and inefficient.
  1 件のコメント
Stephen23
Stephen23 2022 年 4 月 14 日
編集済み: Stephen23 2022 年 4 月 14 日
Simple demo:
PSD1 = 11;
PSD2 = 22;
notPSD = 33;
save('mydata.mat', '-regexp','^PSD')
whos -file mydata
Name Size Bytes Class Attributes PSD1 1x1 8 double PSD2 1x1 8 double

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

カテゴリ

Find more on Workspace Variables and MAT-Files in Help Center and File Exchange

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by