Is there a way to automatically suppress Matlab from printing big matrices in command window?

后端 未结 1 458
故里飘歌
故里飘歌 2021-02-07 09:57

Is there an option in matlab or a plugin/app or a trick such that if you are in an interactive command session, every time it would print out a matrix way too big for a human to

1条回答
  •  青春惊慌失措
    2021-02-07 10:00

    One possibility is to overload the display function, which is called automatically when you enter an expression that is not terminated by ;. For example, if you put the following function in a folder called "@double" anywhere on your MATLAB path, the default display behavior will be overridden for double arrays (this is based on Mohsen Nosratinia's display.m for displaying matrix dimensions):

    % @double/display.m
    function display(v)
    % DISPLAY Display a variable, limiting the number of elements shown.
    
    name = inputname(1);    
    if isempty(name)
        name = 'ans';
    end
    
    maxElementsShown = 500;
    newlines = repmat('\n',1,~strcmp(get(0,'FormatSpacing'),'compact'));
    
    if numel(v)>maxElementsShown,
        warning('display:varTooLong','Data not displayed because of length.');
        % OR show the first N=maxElementsShown elements
        % builtin('disp', v(1:maxElementsShown));
    elseif numel(v)>0,
        fprintf([newlines '%s = \n' newlines], name);
        builtin('disp', v);
    end
    
    end
    

    For example,

    >> xx=1:10
    
    xx = 
    
         1     2     3     4     5     6     7     8     9    10  
    
    >> xx=1:1e4
    Warning: Data not displayed because of length. 
    > In double.display at 17 
    

    EDIT: Updated to respect 'compact' and 'loose' output format preference.

    EDIT 2: Prevent displaying an empty array. This makes whos and other commands avoid an unnecessary display.

    0 讨论(0)
提交回复
热议问题