问题
I'm trying to output a Matrix:
M = [1 20 3; 22 3 24; 100 150 2];
Using:
for i=1:3
fprintf('%f\t%f\t%f\n', M(i), M(i+length(M)), M(i+length(M)*2));
end
And the output is turning out something like:
1 20 3
22 3 24
100 150 2
Which is obviously not great. How can I get it so the front of integers are padded with spaces? Like so:
1 20 3
22 3 24
100 150 2
Any ideas?
Thanks!
回答1:
You can use string formatting to allocate specific number of characters per displayed number.
For example
fprintf('% 5d\n', 12)
prints 12
in 5 characters, padding the un-used 3 leading characters with spaces.
回答2:
You can use num2str (optionally with format string %f
) and apply it to the whole matrix instead of each row so that you get the right padding:
disp(num2str(M));
returns
1 20 3
22 3 24
100 150 2
来源:https://stackoverflow.com/questions/18593083/matlab-output-space-padding