How to selectively save the names and values of some workspace variables to a CSV file?

3 ビュー (過去 30 日間)
Diaa
Diaa 2020 年 9 月 15 日
コメント済み: Diaa 2020 年 9 月 15 日
Consider the following
a = 3; b=7; c=5; d=9;
save('test.mat')
data = load('test.mat');
toSave = { 'b' ; 'c' };
writecell( horzcat( toSave , <missing code> ) ,'myfile.csv')
what should be the <missing code> in order to have the content of myfile.csv to be
b , 7
c , 5
?
  2 件のコメント
Rik
Rik 2020 年 9 月 15 日
Are b and c guaranteed to be scalar?
Diaa
Diaa 2020 年 9 月 15 日
Yes, so far.

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

採用された回答

Rik
Rik 2020 年 9 月 15 日
This should do the trick. If the variables aren't scalars the results might not be what you want.
a = 3; b=7; c=5; d=9;
save('test.mat')
data = load('test.mat');
toSave = { 'b' ; 'c' };
s=struct;
for n=1:numel(toSave)
s.(toSave{n})=data.(toSave{n});
end
writecell( horzcat( toSave , struct2cell(s) ) ,'myfile.csv')
  3 件のコメント
Rik
Rik 2020 年 9 月 15 日
You could also ask load to only retrieve the variables of interest:
s=load('test.mat',toSave{:});
Note that loops have a pretty good performance, as long as you aren't dynamically growing arrays and there isn't a direct function to do it.
Diaa
Diaa 2020 年 9 月 15 日
I totally forgot the simple way of selective loading.
Thanks for the hint.

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

その他の回答 (1 件)

Diaa
Diaa 2020 年 9 月 15 日
Thanks to the inspiring answer of @Rik, I found the following solution without the need to use for loop
a = 3; b=7; c=5; d=9;
save('test.mat')
data = load('test.mat');
toSave = { 'b' ; 'c' };
writecell(horzcat(toSave, cellfun( @(C) data.(C),toSave,'UniformOutput',false)),'myfile.csv')
  2 件のコメント
Rik
Rik 2020 年 9 月 15 日
cellfun will only hide the loop. In general it will be slower that a well-written for loop. Just something to be aware of.
Diaa
Diaa 2020 年 9 月 15 日
You are right, but I can't resist minimizing the code despite knowing it is not the best practice :)

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by