2

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!

Travv92
  • 791
  • 4
  • 14
  • 27
  • I assume you need fprint() to write to file or something, otherwise you can just do `M` with no semicolon and Matlab formats it nicely in the command window. – shoelzer Sep 03 '13 at 13:15
  • I wonder if you have your preferences set improperly, so that a mono-spaced font is not used in the command window. –  Sep 03 '13 at 13:21

2 Answers2

5

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.

Shai
  • 111,146
  • 38
  • 238
  • 371
1

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
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
  • 2
    @Shai If you try both, you see that `disp` adds spaces to the beginning of each line, while `num2str` doesn't and that matches the answer expected by OP. – Mohsen Nosratinia Sep 03 '13 at 13:28