How can I center my table?

1 view (last 30 days)
Dimitri
Dimitri on 13 Mar 2014
Commented: Dimitri on 13 Mar 2014
if true
A = [10 2 -1;-3 -6 2;1 1 5];
b = [27;-61.5;-21.5];
X = zeros(length(b),1);
error = ones(length(b), 1)*100;
iteration = 0;
fprintf('Iteration\t x1\t\t x2\t\t x3\t\tError1\t Error2\t\tError3\t\tMax. error\n')
while max(error) > 5
iteration = iteration + 1;
Z = X;
for i = 1:length(b)
j = 1:length(b);
Xnow = X;
Xnow(i) = 0;
X(i) = (b(i) - sum(A(i,j)*Xnow))/A(i,i);
end
error = abs((X - Z)./X)*100;
fprintf(' %4.0f\t\t%4.5f\t\t%4.5f\t\t%8.5f\t%4.2f%%\t %4.2f%%\t\t%4.2f%%\t %4.2f%%\n', iteration, X(1), X(2), X(3), error(1), error(2), error(3), max(error))
end
end
The code produces the table attached.
How can I straighten the values under Max. error and Error3?

Accepted Answer

dpb
dpb on 13 Mar 2014
Don't use \t, use fixed-width column of the desired width including the spacing desired and include the flag character ' ' in the field to cause right justification in the field.
>> vals=[100.333 40.1 5.23];
>> fprintf('% 12.2f%%\n',vals)
100.33%
40.10%
5.23%
>>
  3 Comments
dpb
dpb on 13 Mar 2014
Yes. You must not have corrected the field widths to be the full width. Observe the second case below carefully--
>> fprintf('%12.2f%%%10.5f\n',[vals' vals'])
100.33% 40.10000
5.23% 100.33300
40.10% 5.23000
>> fprintf('%2.2f%%%10.5f\n',[vals' vals'])
100.33% 40.10000
5.23% 100.33300
40.10% 5.23000
>>
Dimitri
Dimitri on 13 Mar 2014
Never mind, I figured it out. Thank you. :)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!