How can I save different variables in separated files using cellfun/arrayfun?

14 ビュー (過去 30 日間)
Unai Lorenzo
Unai Lorenzo 2017 年 4 月 19 日
コメント済み: Unai Lorenzo 2017 年 4 月 21 日
I would like to save different variables (included in the same cell) using cellfun.
As an example, this is the cell containing the file names for the 3 files that will be created:
fnames={'var1.mat';'var2.mat';'var3.mat'};
And this is the cell with the variables that will be saved in the corresponding files:
vars={ones(1);2*ones(3);3*ones(3)};
As far as I understand, arrayfun could save vars{1} with the name 'var1.mat', vars{2} with the 'var2.mat', and vars{3} with 'var3.mat'. But I get the following error:
cellfun(@(x,y) save(x,y), fnames,vars)
Error using save
Argument must contain a character vector.
Error in @(x,y)save(x,y)
If I try the following code I get another error:
cellfun(@(x,y) save(x,y), fnames,'vars')
Error using cellfun
Input #3 expected to be a cell array, was char instead.
I don't really know if the syntax is not correct or what I'm trying to do is not possible.
Any ideas about it?
Many thanks!!
  1 件のコメント
Stephen23
Stephen23 2017 年 4 月 19 日
Unfortunately this is a major "design feature" (aka mistake) in the function save. Not easy to work around, really.

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

採用された回答

Jan
Jan 2017 年 4 月 19 日
The save command expects the data as the name of the variable. It does not accept the array to be saved directly. If you really need this, write a wrapper:
cellfun(@(x,y) savewrapper(x,y), fnames, vars)
function savewrapper(FileName, Data)
save(FileName, 'Data');
  1 件のコメント
Unai Lorenzo
Unai Lorenzo 2017 年 4 月 21 日
I just wanted to check if I could save the files faster than using a loop, but it also seems slow. Thanks anyway!

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by