How to print 1x50 array into a text file
28 次查看(过去 30 天)
显示 更早的评论
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 个评论
Jan
2019-5-23
编辑:Jan
2019-5-23
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.
采纳的回答
Jan
2019-5-23
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);
更多回答(2 个)
Akira Agata
2019-5-23
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 个评论
Akira Agata
2019-5-23
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
2019-5-23
编辑:Raj
2019-5-23
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!