How to print an array with same column starting locations?

1 次查看(过去 30 天)
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?

采纳的回答

Jos (10584)
Jos (10584) 2018-2-1
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 个评论
Bob Thompson
Bob Thompson 2018-2-1
Ok, yes, this gives what I'm looking for, but I want to make sure I understand what it is doing. I'm assuming repmat means "represent matrix" where each value is a floating number with twelve spaces and four decimal spaces (%12.4f). You indicate that the - sign (%-12.4f) causes an alignment left.
What do the 1 and 2 mean, and why does the array need to be transposed? Also, how would I go about doing something like this with a single line from the array?
Jos (10584)
Jos (10584) 2018-2-1
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by