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?
댓글 수: 0
채택된 답변
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
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 Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!