How to print 1x50 array into a text file
47 views (last 30 days)
Show older comments
Hello,
I have 1x50 array A=[0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340 30.850 .... 0.000]
and want to print them into a text file with the below format.
0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340
30.850 51.460 13.378 4.600 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000
How should I do this?
1 Comment
Jan
on 23 May 2019
Edited: Jan
on 23 May 2019
And what exactly is the "below format"? Do you want spaces or tab stops between the numbers? Tab stops before the line breaks? A fixed number of 8 columns, or does this depend on the number of elements? A trailing linebreak or not? 10 characters per number and 3 digits after the point? Please mention the details.
Accepted Answer
Jan
on 23 May 2019
Maybe:
[fid, msg] = fopen(FileName, 'w');
assert(fid ~= -1, 'Cannot open file for writing: %s\n%s\n', FileName, msg);
fmt = [repmat('%10.3f', 1, 8), '\n'];
fprintf(fid, fmt, A.');
fclose(fid);
More Answers (2)
Akira Agata
on 23 May 2019
How about the following?
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t');
2 Comments
Akira Agata
on 23 May 2019
Dear Hossein-san,
Thank you for your comment.
Sorry, I've missed your 'fprintf' tag in your original post.
Just FYI, your can save as %10.3f format by dlmwrite function, too, by:
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t','precision','%10.3f');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t','precision','%10.3f');
Raj
on 23 May 2019
Edited: Raj
on 23 May 2019
Answer given by Akira is the optimal solution but since you have mentioned 'fprintf' as a tag, here are two ways to get what you want using 'fprintf'
fid=fopen('MyFile.txt','w'); % Open text file
fprintf(fid, '%10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f\r\n',A); % Write 8 elements in each line from A with 3 digits after decimal
fclose(fid); % Close the file
or an even weird way:
fid=fopen('MyFile.txt','w');
for i=1:numel(A)
if rem(i,8)~=0
fprintf(fid, ' %10.3f',A(1,i));
else
fprintf(fid, ' %10.3f\r\n',A(1,i));
end
end
fclose(fid);
Good luck!!
0 Comments
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!