如何以更好的方式在Matlab中显示序列号?

Tid*_* Gu 3 matlab number-formatting

例如,我有一个数组:

a=[1:5 8:10];
Run Code Online (Sandbox Code Playgroud)

如果我使用以下方式显示:

disp(['a = ' num2str(a)]);
Run Code Online (Sandbox Code Playgroud)

结果就像是

a = 1 2 3 4 5 8 9 10

这比我需要的时间太长了.我怎样才能让Matlab以我定义的方式或尽可能接近的方式显示?

更具体地说,如果我以"非正式"方式定义变量,例如:

a=[1:3 4:6 8:10]
Run Code Online (Sandbox Code Playgroud)

(通常应为1:6而不是1:3 4:6)

我只想让Matlab以任何一种方式显示:

1:3 4:6 8:10    or    1:6 8:10
Run Code Online (Sandbox Code Playgroud)

我也不在乎它是否显示变量名称或方括号.

搜索但没有找到任何有用的东西.考虑手动解析它,但听起来不是一个聪明的方法.

任何建议都会很有帮助,非常感谢.

gno*_*ice 5

执行此操作的唯一方法是创建自己的函数以显示所需格式的数组.例如,如果要以压缩方式显示数组中单调递增的部分,可以使用如下函数:

function display_array(array)
    str = cellfun(@(n) {num2str(n)}, num2cell(array));
    index = (diff(array) == 1) & ([1 diff(array, 2)] == 0);
    str(index) = {':'};
    str = regexprep(sprintf(' %s', str{:}), '( :)+\s*', ':');
    disp([inputname(1) ' = [' str(2:end) ']']);
end
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

>> a = [1:5 7 9:11]  %# Define a sample array

a =

     1     2     3     4     5     7     9    10    11     %# Default display

>> display_array(a)
a = [1:5 7 9:11]     %# Condensed display
>> b = [1 2 3 4 4 4 3 2 1];  %# Another sample array
>> display_array(b)
b = [1:4 4 4 3 2 1]  %# Note only the monotonically increasing part is replaced
Run Code Online (Sandbox Code Playgroud)