如何在 Matlab 中用分隔符填充行

How to fill up line with delimiters in Matlab

我有一个元胞数组 A,我希望将其打印为 table。第一列和第一行是 headers。例如我有

 A:
 1     2     3
 4     5     6
 7     8     9

我希望输出如下所示:

 A:
 1   ||2    |3
 -------------
 4   ||5    |6
 7   ||8    |9

竖线没有问题。我只是不知道如何打印出水平线。它应该比 disp('-------') 更灵活。它应该根据我的单元格中的字符串大小来调整大小。

到目前为止,我只实现了只显示静态字符串“-----”的丑陋方式。

function [] = dispTable(table)
basicStr = '%s\t| ';
fmt = strcat('%s\t||',repmat(basicStr,1,size(table,2)-1),'\n');
lineHeader = '------';
%print first line as header:
fprintf(1,fmt,table{1,:});
disp(lineHeader);
fprintf(1,fmt,table{2:end,:});
end

感谢任何帮助。谢谢!

您将无法可靠地计算字段的宽度,因为您使用的制表符的宽度可能因机器而异。此外,如果您尝试以表格结构显示内容,最好避免使用制表符,以防两个值相差超过 8 个字符,这会导致列不对齐。

我不会使用制表符,而是为您的数据使用固定宽度的字段,这样您就知道要使用多少 - 个字符。

% Construct a format string using fixed-width fonts
% NOTE: You could compute the needed width dynamically based on input
format = ['%-4s||', repmat('%-4s|', 1, size(table, 2) - 1)];

% Replace the last | with a newline
format(end) = char(10);

% You can compute how many hypens you need to span your data
h_line = [repmat('-', [1, 5 * size(table, 2)]), 10];

% Now print the result
fprintf(format, table{1,:})
fprintf(h_line)
fprintf(format, table{2:end,:})

%    1   ||2   |3
%    ---------------
%    4   ||7   |5
%    8   ||6   |9