Matlab中如何用分隔符填充行

Matlab中如何用分隔符填充行,matlab,matrix,cell-array,Matlab,Matrix,Cell Array,我有一个单元格数组a,我希望将其打印为表。第一列和第一行是标题。比如我有 A: 1 2 3 4 5 6 7 8 9 我希望输出像这样: A: 1 ||2 |3 ------------- 4 ||5 |6 7 ||8 |9 竖条没有问题。我只是不知道如何打印出水平线。它应该比仅仅disp('----')更灵活。它应该根据单元格中字符串的大小调整大小 到目前为止,我只实现了只显示静态字符串'----

我有一个单元格数组a,我希望将其打印为表。第一列和第一行是标题。比如我有

 A:
 1     2     3
 4     5     6
 7     8     9
我希望输出像这样:

 A:
 1   ||2    |3
 -------------
 4   ||5    |6
 7   ||8    |9
竖条没有问题。我只是不知道如何打印出水平线。它应该比仅仅
disp('----')
更灵活。它应该根据单元格中字符串的大小调整大小

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


感谢您的帮助。谢谢

您无法可靠地计算字段的宽度,因为您使用的选项卡的宽度可能因机器而异。此外,如果您试图以表格结构显示某些内容,最好避免使用制表符,以防两个值相差超过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

这将是困难的,因为您使用的是制表符,并且制表符在空格中的宽度因机器而异。我建议使用带有固定宽度字段的
sprintf
。哇,谢谢。太快了!在我的特殊情况下,恒定宽度是令人窒息的。但我会把这个问题留待一段时间,以防有人知道使用tabs appoach的方法。@VietTran您还希望避免使用tabs,以防一列中的两个值相差超过tab宽度。这将导致列不再对齐。对于这样的显示,固定宽度字段是一种更好的方法。因此,您建议先确定最大宽度长度,然后使用固定宽度方法?@VietTran我将确定您想要向右的填充量,然后计算每列的最大宽度+填充,并将其用作该列的固定宽度。谢谢您的帮助。我现在认为你的方法是正确的。标签处理起来很混乱。如您所述,如果列的差异大于选项卡宽度,则会出现问题。因此,我接受了awnser:)
% 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