例如我有一个数组:
a=[1:5 8:10];
如果我使用以下方式显示它:
disp(['a = ' num2str(a)]);
结果会是这样的
a = 1 2 3 4 5 8 9 10
它比我需要的太长了。如何让 Matlab 显示与我定义的方式相同或接近?
更具体一点,如果我以“非正式”方式定义变量,例如:
a=[1:3 4:6 8:10]
(通常应该是 1:6 而不是 1:3 4:6)
我只想让 Matlab 以任一方式显示:
1:3 4:6 8:10 or 1:6 8:10
我也不关心它显示的是变量名还是方括号。
搜索过但没有找到任何有用的东西。考虑手动解析它,但听起来不是一个聪明的方法。
任何建议都会很有帮助,非常感谢。
最佳答案
做到这一点的唯一方法是创建您自己的函数,以您想要的格式显示数组。例如,如果您想以压缩方式显示数组的单调递增部分,您可以使用如下函数:
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
你会像这样使用它:
>> 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
关于matlab - 如何更好地在 Matlab 中显示序列号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10318292/