How to save multiple text files with same name, but with incrementing numbers

12 ビュー (過去 30 日間)
Hi all,
I need to save multiple text files with the same name, just incrementing numbers at the end of the filename. The function I'm using, writetable, requires to specify the filename between apostrophes, so the function cannot recognize the changing filename, returning as output always the same. Thank you!
str = 'ccc2019RS';
t = 0;
for f = 1:74
t = t + 1;
Filename = [str,num2str(t)];
tab = table(Y(:),M(:),D(:),H(:)),astrF(:,f),ssh2D(:,f),tempF(:,f),salF(:,f));
writetable(tab,'FileName.dat','Delimiter','tab','WriteVariableNames',false);
clear tab FileName
end
  2 件のコメント
Stephen23
Stephen23 2020 年 9 月 22 日
Get rid of this line:
clear tab FileName
It is entirely pointless and unnecessarily slows down your code. Trying to micro-manage MATLAB memory management without really understanding how it works usually results in complex, inefficient code.
Luís Henrique Bordin
Luís Henrique Bordin 2020 年 9 月 22 日
Hi Stephen. Indeed, that line is pointless, thank you!

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

採用された回答

sushanth govinahallisathyanarayana
sushanth govinahallisathyanarayana 2020 年 9 月 22 日
Instead of filename.dat, you could substitute
['myFilename_',num2str(i),'.dat], as the loop increments, it will create a new name.
Hope this helps,

その他の回答 (1 件)

Stephen23
Stephen23 2020 年 9 月 22 日
編集済み: Stephen23 2020 年 9 月 22 日
"The function I'm using, writetable, requires to specify the filename between apostrophes..."
Actually the writetable documentation states that the filenames must be specified by a character vector or a scalar string. In either case it makes no difference if the name is specified in the function call or supplied as a variable.
"so the function cannot recognize the changing filename"
Actually it does (just like all MATLAB function that read/write file data do). For example, you could do this:
fnm = sprintf('%s%d.dat',str,t);
..
writetable(tab,fnm,..);
Read more:
  1 件のコメント
Luís Henrique Bordin
Luís Henrique Bordin 2020 年 9 月 22 日
Sorry for my ignorance, I am a beginner, and I have difficulty understanding how to structure the sprintf function. The option sugested by Sushanth was usefull, nevertheless, I'll try to use sprintf in the future, thank you!

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by