필터 지우기
필터 지우기

write multiple line of text into a text file

조회 수: 77 (최근 30일)
Ali
Ali 2017년 8월 3일
댓글: Walter Roberson 2017년 8월 5일
Simple question; I have this variable which I want easily write to a text file (it can be a hundred of lines, I just cut it into 4 to fit here)
app.DCMtxt.Value
ans =
4×1 cell array
'3 Message(s) transmitted '
''
' ws BUS ID Rx Node DLC Cycle Extended'
' ______ ___ ____ __ ____ ___ _____ ________'
  댓글 수: 4
Ali
Ali 2017년 8월 4일
편집: Ali 2017년 8월 4일
Thanks for the replies. Per, it does not write to the file. I also get: Warning: Escaped character '\s' is not valid. See 'doc sprintf' for supported special characters. I see it reads it line by line, nice!
Ali
Ali 2017년 8월 4일
looks like Per's answer had a typo and otherwise working well, so I'm reposting it with minor change as an answer
fid = fopen('output.txt','w');
for jj = 1 : size( app.DCMtxt.Value, 1 )
fprintf( fid, '%s\n', app.DCMtxt.Value{jj,1} );
end
fclose(fid);

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

채택된 답변

Walter Roberson
Walter Roberson 2017년 8월 4일
fid = fopen('output.txt','w');
fprintf(fid, '%s\n',app.DCMtxt.Value{:}) ;
fclose(fid) ;
  댓글 수: 4
Rik
Rik 2017년 8월 5일
You might need to replace the control characters:
escaped_cellstr=app.DCMtxt.Value;
escaped_cellstr=strrep(escaped_cellstr,'%','%%');
escaped_cellstr=strrep(escaped_cellstr,'/','//');
fid = fopen('output.txt','w');
fprintf(fid, '%s\n',escaped_cellstr) ;
fclose(fid) ;
Walter Roberson
Walter Roberson 2017년 8월 5일
No, Rik, that is not needed. That would only be needed if you were using the string content inside the format. For example, the following would be a problem:
fid = fopen('output.txt','w');
for jj = 1 : size( app.DCMtxt.Value, 1 )
fprintf( fid, app.DCMtxt.Value{jj,1} );
fprintf( fid, '\n' );
end
fclose(fid);

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

추가 답변 (1개)

Will Wilson
Will Wilson 2017년 8월 4일
If you didn't want to use a for loop directly you could use a newer datatype called a table and one if it's helper functions to get the job done. Here is an example:
% Convert your [m x 1] cell array into a MATLAB table.
data = cell2table(app.DCMtxt.Value);
% (Optionally) name the column in your table.
data.Properties.VariableNames = {'DataSet'};
% Write the table out to a text file.
writetable(data,'OutputData');
This should do the trick. Ultimately it will depend on how much control you need on the text file you write out.

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by