string - MATLAB 中的 num2str 自动宽度格式

string - num2str auto width format in MATLAB

抱歉我的愚蠢问题,我是 matlab 的新手。 我有一个这样的矩阵数组

num = [
    4.2, 3, 5;
    3, 12.1, 3.4;
    2, 5.22, 4
]

我只想使用中心对齐格式显示它,如下例

但是 num 数组中的数字是动态的,有时每行最多包含 4 个或更多这样的数字

num = [
    4.2, 3, 5, 7.899;
    3, 12.1, 3.4, 89;
    2, 5.22, 4, 9.1
]

我正在尝试使用 num2str() 函数,但它不适合我的情况,因为我的数据是动态的(有时它总是有 2 或 3 位小数号码)这是我的代码:

num2str('%10.1f \t %10.1f \t %10.1f \n', num);

除了使用num2str()还有其他功能吗,因为我的数组数据是动态的

您可以将字符串居中 strjust. Here, I build the individual elements in a loop with sprintf 并添加换行符:

num = [
4.2, 3, 5, 7.899;
3, 12.1, 3.4, 89;
2, 5.22, 4, 9.1
];

% Loop over rows (ii) and columns (jj) of num
output = '';
for ii = 1:size(num,1)
  for jj = 1:size(num,2)
    output = [output, strjust(sprintf('%10.4g',num(ii,jj)),'center')];
  end % for jj
  output = [output, '\n'];
end % for ii
fprintf(output)

输出:

   4.2        3         5       7.899   
    3        12.1      3.4        89    
    2        5.22       4        9.1    

您可以将其放入例如使用最终调用 sprintf:

的图像
text(0.5, 0.5, sprintf(output))

请注意,这使用了 non-fixed 宽度的字体,因此长行可能看起来不像 centre-justified。这可以通过使用

看到
num = [999, 999, 999, 999; 1, 1, 1, 1];

MATLAB 版本 R2014a.