如何在 Matlab 中正确地用空格扩展制表符 \t?

How to Expand Tab Symbol \t with Spaces Correctly in Matlab?

情况:无法找到 setting/one-liner 将制表符 \t 扩展为四个空格,以及为什么在 Matlab

x 960 之间的代码中奇怪地添加空格
fprintf('Counter \t Free memory / GB \t Along... \t Image R \n');
fprintf('%6.0f \t %6.2f \t %6.2f \t %6.0f x %6.0f \n', ...
    counter, ...
    totalFree, perc, ...
    imageResolutionHeight, imageResolutionWidth); 

您将制表符大小视为不包含空格的选择的输出

  1. \t 没有用空格展开
  2. Matlab 在 xx960 中的第二个数字 (960) 之间放置空格,尽管代码只是 %6.0f x %6.0f

图1 在首选项 > Editor/Debugger > 我有 Tab keys insert spaces 的选项卡中没有相关,但它与扩展选项卡符号 \t 无关,图 2 在首选项 > 键盘

中没有相关

系统:Linux Ubuntu 16.04 64 位
Matlab: 2016a
文档:Editor/Debugger Preferences,...

格式规范%6.0f x %6.0f指定每个数字都是一个floating-point数字,字段宽度为六位,小数点后为零。因此,由于数字只有960,因此必须在该数字前插入三个空格。

看看documentation,解释的很好。

\t是tab的ASCII码,不是四个空格。你可能在编辑器中得到四个空格,但在字符串中它是明确的,它是 ASCII 代码点 9。最简单和最干净的方法可能只是直接用四个空格替换制表符字符串使用 regexprep:

str = 'Counter \t Free memory / GB \t Along... \t Image R \n'
updatedString = regexprep(str, '\t' , '    ');

对了,我猜你想要的格式是:

fprintf('Counter \t Free memory / GB \t Along... \t Image R \n');
fprintf('%7.0f \t %16.2f \t %8.2f \t %3.0f x %i \n', numbers)
Counter      Free memory / GB    Along...    Image R 
      2                 19.05        0.19    960 x 960 
      3                 14.29        0.14    960 x 1920 
      4                 15.68        0.15    960 x 2880 
      5                  2.40        0.02    960 x 3840

请注意,所有数字占用的字符数与上述 headers 相同。更简单的方法当然是将所有列名存储在一个单元格中,然后统计每个单元格中的字符数来确定相应数字的长度。

或使用table!

我建议不要使用 and/or 替换 \t,而是使用定义的格式规范打印标题:

fprintf('% 8s% 24s% 16s% 16s\n', 'Counter', 'Free memory / GB' ...
    'Along...', 'Image R');

字段宽度前的白色space 会导致fprintf 填写尽可能多的space 个字符以获得所需的字段宽度。这记录在 format spec documentation -> 可选运算符 -> 标志中。

现在使用相同的字段宽度打印数字。

fprintf('%8u%24.2f%16.2f%9u x %4u\n', ...
    counter, totalFree, perc, ...
    imageResolutionHeight, imageResolutionWidth);

我的测试结果输出:

 Counter        Free memory / GB        Along...         Image R
       1                   26.63           25.00      960 x  960
       2                   26.65           50.00      960 x 1920
       3                   26.33           75.00      960 x 2880
       4                   26.02          100.00      960 x 3840