How do I make my fprintf columns output neatly?
34 次查看(过去 30 天)
显示 更早的评论
I have some code that generates x, y, and z data points that I want to output to a text file in columns. I can't have a bunch of 0s, so I've replaced the 0s with NaN in my vectors. When I go to output my code, this makes the columns look funny. How can I make it so that there is extra spacing included in the points where a NaN value exists so that everything stays in 3 columns?
close all
clear
clc
dataPoints = [NaN NaN NaN NaN NaN NaN NaN 1 2 3 4;
157.66 157.66 157.66 157.66 157.66 157.66 157.66 157.66 157.66 157.66 157.660;
NaN NaN NaN NaN NaN NaN 67.1064 67.115646 67.144455 67.194319 67.267807];
fileNameOut = 'output.txt';
fid = fopen(fileNameOut,'w');
fprintf(fid,'x\t\ty\t\tz\n');
fprintf(fid,'%f\t%f\t%f\n',dataPoints);
fclose all;
This generates a text file that looks like this
x y z
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 67.106400
1.000000 157.660000 67.115646
2.000000 157.660000 67.144455
3.000000 157.660000 67.194319
4.000000 157.660000 67.267807
But I need it to look more like this
x y z
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 NaN
NaN 157.660000 67.106400
1.000000 157.660000 67.115646
2.000000 157.660000 67.144455
3.000000 157.660000 67.194319
4.000000 157.660000 67.267807
0 个评论
回答(1 个)
Riccardo Scorretti
2022-5-6
Hi. I think it is better to work with fixed length fields rather than tabulations (which have the problem of being system-dependent). Just try like this:
fprintf(fid,'%11.6f %11.6f %11.6f\n',dataPoints);
Of course you can adjust the numbers 11 (= minimal number of characters) and 6 (= number of decimal numbers) to your personal needs.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!