Saving the .mat file using for loop

8 ビュー (過去 30 日間)
Aftab Ahmed Khan
Aftab Ahmed Khan 2014 年 5 月 28 日
コメント済み: Roger Wohlwend 2014 年 5 月 28 日
Hi everyone,
I have the following section of code. I want to generate 10 different files using the for loop and each time i want to save each generated random_sample to be saved as a separate data file. So by the end of the for loop i should have 10 different files in total with different names. What is the missing part in the save-command line. Thank you.
lambda = 2;
for i = 1:10
random_sample = poissrnd(lambda,1,100)>0.25;
save('datafile','random_sample');
end

採用された回答

Roger Wohlwend
Roger Wohlwend 2014 年 5 月 28 日
You use the same file name for all ten samples. So Matlab overrides the file in every iteration and you end up with one saved sample only. What you have to do is make the file name dependent on the iteration. You could do that as follows:
save(sprintf('datafile_%02d',i), 'random_sample');
That should do it.
  2 件のコメント
Aftab Ahmed Khan
Aftab Ahmed Khan 2014 年 5 月 28 日
Hi Roger,
That exactly what i wanted to achieve.
Can you just explain to me the "%02d" part in the command ?
Thank you.
Roger Wohlwend
Roger Wohlwend 2014 年 5 月 28 日
Of course. With the "%02d" part I tell the sprintf function what to do: convert the integer i to a string and use (at least) two digits. That means, sprintf converts 1 into the string "01", 2 into "02", and so on.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMigrate GUIDE Apps についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by