How to print an array with same column starting locations?

1 view (last 30 days)
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?

Accepted Answer

Jos (10584)
Jos (10584) on 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 Comments
Bob Thompson
Bob Thompson on 1 Feb 2018
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) on 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!