Matlab output - Space padding?

穿精又带淫゛_ 提交于 2020-01-13 19:56:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!