Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 look through, it redacts the output to either a warning of how big the matrix is or a summary (only a few rows and columns) of the matrix?

There are many times where I want to examine a matrix in the command window, but I didn't realize how big it was, so I accidentally printed the whole thing out. Or some place inside a function I did not code myself, someone missed a semicolon and I handed it a big matrix, and it dumps the whole thing in my command window.

It make sense that in 99.99% of the time, people do not intend to print a million row matrix in their interactive command window, right? It completely spams their scroll buffer and removes all useful information that you had on screen before.

So it makes much more sense for matlab to automatically assume that the user in interactive sessions want to output a summary of a big matrix, instead of dumping the whole thing into the command window. There should at least be such an option in the settings.

like image 672
BW0 Avatar asked Nov 06 '13 18:11

BW0


1 Answers

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.

like image 63
chappjc Avatar answered Sep 22 '22 19:09

chappjc