简体   繁体   中英

How to display sequence numbers in Matlab in a better way?

For example, I have an array:

a=[1:5 8:10];

If I display it using:

disp(['a = ' num2str(a)]);

The result would be something like

a = 1 2 3 4 5 8 9 10

It's quite too long than I need. How can I let Matlab to display as same as the way I defined it or as close as is?

Be more specific, if I defined the variable in an "informal" way like:

a=[1:3 4:6 8:10]

(should be normally 1:6 instead of 1:3 4:6)

I just want Matlab to display in either way:

1:3 4:6 8:10    or    1:6 8:10

I also not care about whether it displays the variable name or square brackets.

Searched but didn't find anything useful. Considered to manually parse it but doesn't sounds like a clever way.

Any suggestion would be great helpful, thanks a lot.

The only way to do this would be to create your own function to display the arrays in the format you want. For example, if you want to display monotonically-increasing portions of your array in a condensed fashion, you could use a function like this:

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

And you would use it like so:

>> 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

For this, I use vec2str from the Matlab file exchange. For example:

str = vec2str([1 3 5 5 9 8 7 6 5]) 
ans = 
    [1:2:5,5,9:-1:5] 

>> eval(str) 
ans = 
     1 3 5 5 9 8 7 6 5 

Impossible. Matlab throws away your definition very quickly. The "object" a has no knowledge of that definition at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM