How do I make my fprintf columns output neatly?

32 visualizaciones (últimos 30 días)
Isaac Gruver
Isaac Gruver el 6 de Mayo de 2022
Comentada: Isaac Gruver el 11 de Mayo de 2022
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

Respuestas (1)

Riccardo Scorretti
Riccardo Scorretti el 6 de Mayo de 2022
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.

Categorías

Más información sobre Specifying Target for Graphics Output en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by