How to print an array with same column starting locations?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Bob Thompson
am 1 Feb. 2018
Kommentiert: Jos (10584)
am 1 Feb. 2018
I have an array with varying size data values:
A = [ 1.1 2.123 3.12
1 45.1234 567
1.23 -3.1 7.34567]
I would like to print the array to a file so that it displays with a flush column starting location as shown. I don't mind going line by line through a for loop, but the size of the array is open to variance, so I cannot go manually line by line.
I have tried using %f designation within fprintf, but this fixes the location of the decimal rather than the first character. I have also tried %e and %g as I don't mind having extra zeroes at the end, however, these two do not properly account for the negative value as shown below.
for I = 1:3
fprintf(file,'%1.6e %1.6e %1.6e\n',A(I,:));
end
1.100000e+00 2.123000e+00 3.120000e+00
1.000000e+00 4.512340e+01 5.670000e+02
1.230000e+00 -3.100000e+00 7.345670e+00
Is there some command other than fprintf which can perform this output, or is there some setting within fprintf which can produce the consistent column locations I would like?
0 Kommentare
Akzeptierte Antwort
Jos (10584)
am 1 Feb. 2018
Something like this? You can specify left alignment using the - sign
fprintf([repmat('%-12.4f',1,size(A,2)) '\n'], A.') % note the transpose
2 Kommentare
Jos (10584)
am 1 Feb. 2018
The '%-12.4f' is a format specifier for fprintf, meaning that it will take a number, print it using 12 positions, aligned to the left ('-') and with 4 decimal positions.
All the other things are just tricks to make it a one-liner. For readability you could consider a double for loop:
for r = 1:size(A,1) % loop over rows
for c = 1:size(A,2) % loop over columns
fprintf('%-12.4f', A(r,c)) ; % print single element
end
fprintf('\n') ; % new line after each row
end
repmat means REPeat MATrix.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!