필터 지우기
필터 지우기

Write data from for loop into a file

조회 수: 3 (최근 30일)
Anna Cole
Anna Cole 2018년 10월 17일
편집: Stephen23 2018년 10월 17일
I want to write a file that displays the following output:
period 1 step 1
save
period 1 step 2
save
period 2 step 1
save
The for loop creates the correct output I want but creates an empty .txt file.
for i=1:951
for j=1:2
s=fprintf('period %d step %d \n\tsave\n',i,j);
end
end
fileID = fopen('SA_SP951.txt','w');
fprintf(fileID,s);
fclose(fileID);

채택된 답변

Stephen23
Stephen23 2018년 10월 17일
편집: Stephen23 2018년 10월 17일
You need to open the file before the loop, print the text inside the loop, and close the file after the loop:
[fid,msg] = fopen('SA_SP951.txt','wt');
assert(fid>=3,msg)
for ii = 1:951
for jj = 1:2
fprintf(fid, 'period %d step %d \n\tsave\n', ii, jj)
end
end
fclose(fid);
Or alternatively you could collect the character vectors that you generate inside loop into one array (e.g. a cell array) (which seems to be what you were trying to do), but this would be more complex, less efficient, and has no obvious benefit for your requirements.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by