How do I make my fprintf columns output neatly?

조회 수: 54 (최근 30일)
Isaac Gruver
Isaac Gruver 2022년 5월 6일
댓글: Isaac Gruver 2022년 5월 11일
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

답변 (1개)

Riccardo Scorretti
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 CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by