How to write a multi-line text data into a text file via MatLab script?
How to write a multi-line text data into a text file via MatLab script?
How to write a multi-line text data into a text file via MatLab script?
How to write a multi-line text data into a text file via MatLab script?
[Ans]
compose cmd and fprintf cmd.
[description]
remember that how to write single-line text data into a text file via MatLab script?
It’s quit simple. There are two ways.
First way:
use fopen to create a file identifier (fid)then use fwrite cmd to write s to fid.
More details on the following hyperlink.
[code]
filename=’test.txt’;
s=’Hello MatLab’;
fid=fopen(filename,’w’);
fwrite(fid,s);
fclose(fid);
Second way:
use fopen to create a file identifier (fid).
then use fprintf to write the s to fid with specified format.
More details on the following hyperlink.
[code]
filename=’test.txt’;
s=’Hello MatLab’;
fid=fopen(filename,’w’);
fprintf(fid,’%s’,s);
fclose(fid);
tran
[P.S.]
(1)fwrite v.s. fprintf
(1–1)fwrite can only be written with single line data.
fwrite can NOT be specified with specified format.
(1-2)fprintf can be written with multi-line data.
You must specify format in fprintf function.
And do you remember that compose string with compose function.
compose function can translate escape-character sequence.
More details on the following hyperlink.
Now, come back to multi-line data writting.
First, we can use compose function to translate it to multi-line strings.
Then, we create file identifier (fid) using fopen function.
Finally, we write mulit-line data using fprintf function.
[code]
clear clc filename=’test.txt’; fID=fopen(filename,’w’); s=”echo Hello\n:reckon\necho shit\n reckon”; s=compose(s); fprintf(fID,’%s\n’,s) fclose(fID);
[ref]
(1)fwrite
Write data to binary file — MATLAB fwrite — MathWorks Switzerland
(2)fprintf
From MatLab documentation.
Write data to text file — MATLAB fprintf — MathWorks Switzerland
From MatLab Answers. Thanks Walter Roberson gave me this idea.
write multiple line of text into a text file — (mathworks.com)
(3)compose
Format data into multiple strings — MATLAB compose — MathWorks Switzerland
메타데이터
- post_id
- f2b1eff38264
- slug
- how-to-write-a-multi-line-text-data-into-a-text-file-via-matlab-script-f2b1eff38264
- url
- https://medium.com/@jayw711kb/how-to-write-a-multi-line-text-data-into-a-text-file-via-matlab-script-f2b1eff38264
- canonical_url
- https://medium.com/@jayw711kb/how-to-write-a-multi-line-text-data-into-a-text-file-via-matlab-script-f2b1eff38264
- author_url
- https://medium.com/@jayw711kb
- status
- ok
- fetched_at
- 2026-07-27 15:08:01