Paste Strings to Text File

조회 수: 4 (최근 30일)
Kevin
Kevin 2014년 6월 25일
댓글: José-Luis 2014년 6월 26일
I need help performing what I believe to be a relatively simply task:
I have code that uses a loop to generate a string (of variable length) with each loop iteration. I want to paste all the generated strings to a text file, with each string on its own line. The strings should be ordered in the text file by the order in which they are generated by the loop.
Can anyone offer help?
Thanks.
  댓글 수: 1
José-Luis
José-Luis 2014년 6월 25일
편집: José-Luis 2014년 6월 25일
How about storing all the strings in a cell array and saving all at once? You could also append to a file each time that a string is created but that is bound to be slower.
Some functions you might want to use:
doc fopen
doc fprintf

댓글을 달려면 로그인하십시오.

채택된 답변

José-Luis
José-Luis 2014년 6월 25일
your_text = cell(10,1);
for ii = 1:10
your_text(ii) = {'Lorem ipsum'};
end
your_text(10) = {'No!'};
fid = fopen('test.txt','w');
fprintf(fid,'%s\n',your_text{:});
fclose(fid)
  댓글 수: 3
Kevin
Kevin 2014년 6월 26일
To clarify, when I view 'test.txt' in MATLAB or Notepad++, the strings are on separate lines. But when I view the file in regular Notepad, they are on one line. Very strange.
Anyhow, I found a work-around by converting the cell array to a one-column table, then pasting that.
José-Luis
José-Luis 2014년 6월 26일
You must be using Windows:
fprintf(fid,'%s\r\n',your_text{:});

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by