create txt files with specific names

24 ビュー (過去 30 日間)
jason lee
jason lee 2020 年 7 月 13 日
編集済み: Stephen23 2020 年 7 月 13 日
i want to create a series of txt files with predefined char names.
here is my code
s = {'RSN1','RSN2','RSN3'};
for i = 3:1:1
fopen([s{i},'.txt'],'w');
end
unfortunately, it dosen't work.
but if i input
s = {'RSN1','RSN2','RSN3'};
fileID = fopen([s{1},'.txt'],'w');
it worked, a txt file named 'RSN1.txt' is created.
so, why it dosen't works with a for loop?
thank you
  2 件のコメント
Stephen23
Stephen23 2020 年 7 月 13 日
Have you looked at how many values this vectors actually has (hint: zero):
for i = 3:1:1
% ^^^^^ how many elements does this have (hint: zero)
Because that vector has zero values, you loop iterates zero times. Probably you want to make the step -1.
"by the way, the syntax fileID(i) = fopen([s{i},'.txt'],'w'); can not be found in MATLAB documentations, but it works with no warning or errors"
I don't see any obvious reason why it should throw any error or show any warning. In any case it is explained in the documentation: array concatenation is explained here:
and fopen is unsurprisingly explained in the fopen documentation. The fact that you combined array concatenation and fopen is not something that needs to be documented (nor could it be documented, it would be impossible to document every permutation of all MATLAB operations).
"a problem is how to pre-allocate fileID for its value will be changed within a for loop."
You don't need to, and in fact there is absolutely no point in your storing the file ID from every file that you open: because you close those files within the same loop iteration the file IDs are useless (ltierally you cannot do anything with them), so there is no point to keeping them hanging around.
s = {'RSN1','RSN2','RSN3'};
for k = 1:numel(s)
fnm = sprintf('%s.txt',s{k});
fid = fopen(fnm,'w');
fprintf(fid,'%d',k);
fclose(fid);
end

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

採用された回答

madhan ravi
madhan ravi 2020 年 7 月 13 日
編集済み: madhan ravi 2020 年 7 月 13 日
for ii = 3:-1:1
Use sprintf() to generate filenames:
sprintf('RSN%d.txt', ii)
  2 件のコメント
madhan ravi
madhan ravi 2020 年 7 月 13 日
“sometimes, the file name could be rather complex, so i want a more general way.”
sprintf() is the general way.
“why?”
No idea.

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

その他の回答 (0 件)

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by