Display matrix with row and column labels

前端 未结 6 1830
误落风尘
误落风尘 2020-12-01 14:08

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


        
6条回答
  •  眼角桃花
    2020-12-01 14:55

    Matthew Oberhardt, usefull code, I added the name to the matrix, here is it the new code so simple just added one more variable And also I let an example to use it, notice that conv is a mxn matrix.

    ---------------CODE---------------

    function out = dispmat(M,name,row_labels,col_labels);
    %% Matthew Oberhardt 
    % 02/08/2013
    % intended to display a matrix along with row and column labels. 
    %% ex:
    % M = rand(2,3);
    % row_labels = {'a';'b'};
    % col_labels = {'c 1','c2 ','c3'};
    % % if there are no labels for rows or cols, put '' as the input.
    % row_labels = '';
    
    %Modified 14.07.2014
    %Nestor Cantu
    %Added the name of the matrix.
    
    %% check that the row & col labels are the right sizes
    [nrows,ncols] = size(M);
    
    %% populate if either of the inputs is empty 
    if isempty(row_labels)
    row_labels = cell(1,nrows);
        for n = 1:nrows
            row_labels{1,n} = '|'; 
        end
    end
    if isempty(col_labels)
        col_labels = cell(1,ncols);
        for n = 1:ncols
            col_labels{1,n} = '-';
        end
    end
    
    assert(length(row_labels)==nrows,'wrong # of row labels');
    assert(length(col_labels)==ncols,'wrong # of col labels');
    
    row_labels = reshape(row_labels,1,length(row_labels));
    col_labels = reshape(col_labels,1,length(col_labels));
    
    %% remove spaces (since they are separators in printmat.m
    cols = strrep(col_labels, ' ', '_');
    rows = strrep(row_labels, ' ', '_');
    
    %% create labels, space delimited
    c_out = [];
    for n = 1:length(cols)
        c_out = [c_out,cols{n},' '];
    end
    c_out = c_out(1:end-1);
    r_out = [];
    for n = 1:length(rows)
        r_out = [r_out,rows{n},' '];
    end
    r_out = r_out(1:end-1);
    
    %% print
    
    printmat(M,name,r_out,c_out)
    
    
    end
    

    ----------EXAMPLE with matrix conv(5,4)--------------

    [m n] = size(conv);
    for i=1:n
        col{i} = ['K = ' num2str(i)];
    end
    
    for i=1:m
        row{i} = ['n =' num2str(i)];
    end
    
    outMat(conv,'Convergence',row',col);
    

    --------------RESULT--------------------------

    Convergence = 
                     K_=_1        K_=_2        K_=_3        K_=_4        K_=_5
         n_=1      0.74218      0.42070      0.11101 9.86259e-006 9.86259e-006
         n_=2      0.49672      0.26686      0.00233 4.46114e-011 4.46114e-011
         n_=3      0.01221      0.00488 1.23422e-007            0            0
         n_=4      0.00010 7.06889e-008 7.06889e-008            0            0
    

提交回复
热议问题