Save uniquely named variables in loop to a certain location

2 ビュー (過去 30 日間)
Roel
Roel 2018 年 4 月 23 日
コメント済み: KSSV 2018 年 4 月 23 日
Hello everyone,
I am running a loop where a variable U is calculated and saved in a .mat file under a unique name every iteration. To name the .mat file I use sprintf:
for j:length(d)
% Long calculation of U left out
save(sprintf('U%02d',j+1), 'U', '-v7.3');
end
Each U is now saved in a .mat file named with the iteriation number with two digits after 'U' and in mat version 7.3. This works great.
However, I would also like define the folder location where the .mat file is saved. I know how to do this using the save command without sprintf but I can't seem to get this to work in combination with sprintf.
Any help is greatly appreciated,
Thank you, Roel

採用された回答

Stephen23
Stephen23 2018 年 4 月 23 日
編集済み: Stephen23 2018 年 4 月 23 日
Do NOT concatenate paths/directories. The recommended method is to use fullfile:
fullname = fullfile(dir1path,dir2path,...,filename)
This will automatically take into account the required file separators. For your case, something like this:
sdp = some directory path
for k = 1:numel(d)
% Long calculation of U left out
fnm = sprintf('U%02d.mat',k+1);
save(fullfile(sdp,fnm), 'U', '-v7.3')
end
  2 件のコメント
Roel
Roel 2018 年 4 月 23 日
Thank you,
I had never heard of fullfile, great!
Stephen23
Stephen23 2018 年 4 月 23 日
編集済み: Stephen23 2018 年 4 月 23 日

@Roel: you should use fullfile, as it handles the file separator quite nicely.

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

その他の回答 (1 件)

KSSV
KSSV 2018 年 4 月 23 日
path = pwd ; % Give your path here
filename = [pwd,filesep,sprintf('U%02d',j+1)]
By the way, you need not save data of iteration into different .mat files. You can save them into a 3D matrix or cell and save it into a singl mat file.
  3 件のコメント
Roel
Roel 2018 年 4 月 23 日
Thanks KSSV, this solves my problem.
I want different .mat files because of RAM issues. Saving the data into one matrix or mat causes an 'out of memory error' on my system.
Thanks again!
KSSV
KSSV 2018 年 4 月 23 日
Still...you can append data into single mat file...

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by