Display matrix with row and column labels

nibot picture nibot · Jul 2, 2011 · Viewed 75.7k times · Source

Is there a convenient way to display a matrix with row and column labels in the Matlab terminal? Something like this:

M = rand(5);
displaymatrix(M, {'FOO','BAR','BAZ','BUZZ','FUZZ'}, ...
                 {'ROW1','ROW2','ROW3','ROW4','ROW5'});    %??

yielding:

        FOO       BAR       BAZ       BUZZ      FUZZ
ROW1    0.1622    0.4505    0.1067    0.4314    0.8530
ROW2    0.7943    0.0838    0.9619    0.9106    0.6221
ROW3    0.3112    0.2290    0.0046    0.1818    0.3510
ROW4    0.5285    0.9133    0.7749    0.2638    0.5132
ROW5    0.1656    0.1524    0.8173    0.1455    0.4018

Even better would be something with some ASCII-art niceties:

     |   FOO       BAR       BAZ       BUZZ      FUZZ
-----+-------------------------------------------------
ROW1 |   0.1622    0.4505    0.1067    0.4314    0.8530
ROW2 |   0.7943    0.0838    0.9619    0.9106    0.6221
ROW3 |   0.3112    0.2290    0.0046    0.1818    0.3510
ROW4 |   0.5285    0.9133    0.7749    0.2638    0.5132
ROW5 |   0.1656    0.1524    0.8173    0.1455    0.4018

Answer

Utku Türer picture Utku Türer · Nov 11, 2012

Matlab has a function called printmat in the Control Systems toolbox. It's in the directory "ctrlobsolete", so we can assume that it is considered "obsolete", but it still works.

The help text is:

>> help printmat
 printmat Print matrix with labels.
    printmat(A,NAME,RLAB,CLAB) prints the matrix A with the row labels
    RLAB and column labels CLAB.  NAME is a string used to name the 
    matrix.  RLAB and CLAB are string variables that contain the row
    and column labels delimited by spaces.  For example, the string

        RLAB = 'alpha beta gamma';

    defines 'alpha' as the label for the first row, 'beta' for the
    second row and 'gamma' for the third row.  RLAB and CLAB must
    contain the same number of space delimited labels as there are 
    rows and columns respectively.

    printmat(A,NAME) prints the matrix A with numerical row and column
    labels.  printmat(A) prints the matrix A without a name.

    See also: printsys.

Example:

>> M = rand(5);
>> printmat(M, 'My Matrix', 'ROW1 ROW2 ROW3 ROW4 ROW5', 'FOO BAR BAZ BUZZ FUZZ' )

My Matrix = 
                       FOO          BAR          BAZ         BUZZ         FUZZ
         ROW1      0.81472      0.09754      0.15761      0.14189      0.65574
         ROW2      0.90579      0.27850      0.97059      0.42176      0.03571
         ROW3      0.12699      0.54688      0.95717      0.91574      0.84913
         ROW4      0.91338      0.95751      0.48538      0.79221      0.93399
         ROW5      0.63236      0.96489      0.80028      0.95949      0.67874