MATLAB Answers

Write multi-line strings into text file?

조회 수: 236(최근 30일)
Xiaohan Du
Xiaohan Du 5 Mar 2018
답변: Stephane 12 Feb 2021 11:55
Hi all,
I have a few lines of strings, which I'd like to write into a .inp (basically a text) file. The strings look like this:
>> strTest
strTest =
6×1 string array
"*Heading"
"** Job name: L2H1_dynamics Model name: Model-1"
"** Generated by: Abaqus/CAE 6.12-4"
"*Preprint, echo=NO, model=NO, history=NO, contact=NO"
"**"
"** PARTS"
I tried to use the following code to write it:
fid = fopen('strTestOtpt.inp', 'wt');
fprintf(fid, strTest);
fclose(fid);
got this error:
Error using fprintf
Invalid format.
I know I can probably use a loop to do this, but is there a better way? Many thanks!

  댓글 수: 0

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

채택된 답변

Xiaohan Du
Xiaohan Du 5 Mar 2018
found an answer here:
code is:
fid = fopen('strTestOtpt.inp', 'wt');
fprintf(fid, '%s\n', strTest);
fclose(fid);

  댓글 수: 0

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

추가 답변(2개)

Pawel Jastrzebski
Pawel Jastrzebski 5 Mar 2018
You're missing the format parameter of the 'fprintf' function:
fid = fopen('strTestOtpt.inp', 'wt');
formatSpec = '%s\n'
fprintf(fid, formatSpec, strTest);
fclose(fid);

  댓글 수: 0

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


Stephane
Stephane 12 Feb 2021 11:55
You can use this oneliner to:
writematrix( strTest , 'strTestOtpt.inp' );

  댓글 수: 0

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

Community Treasure Hunt

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

Start Hunting!

Translated by