How to output matrix dimensions together with its content?

后端 未结 5 827
醉话见心
醉话见心 2021-01-02 02:05

Is it possible to make GNU Octave to output matrix dimensions together with its content? For example, it should produce smth. like this:

octave:1> X = [1          


        
5条回答
  •  旧巷少年郎
    2021-01-02 02:41

    Here is another one. You could either use it to overload @double/display as others have explained, or name it something else and use it as your own custom display function:

    function display(x)
        % determine whether format is loose or compect
        loose = strcmp(get(0,'FormatSpacing'), 'loose');
    
        % print name or ans
        name = inputname(1);
        if isempty(name), name = 'ans'; end
        if loose, disp(' '); end
        disp([name ' =']);
        if loose, disp(' '); end
    
        % print size
        sz = size(x);
        if length(sz) == 2
            fprintf('    %s: %d-by-%d\n', class(x), sz(1), sz(2));
        elseif length(sz) == 3
            fprintf('    %s: %d-by-%d-by-%d\n', class(x), sz(1), sz(2), sz(3));
        else
            fprintf('    %s: %d-D\n', class(x), numel(sz));
        end
        if loose, disp(' '); end
    
        % print array
        disp(x);
    end
    

    Note that I changed the format of the output a little bit from what you had:

    >> format compact;
    >> x = magic(5);
    >> display(x)
    x =
        double: 5-by-5
        17    24     1     8    15
        23     5     7    14    16
         4     6    13    20    22
        10    12    19    21     3
        11    18    25     2     9
    

提交回复
热议问题