How can I add row and column headers to a Matlab matrix?

10,149

If you have the Statistics Toolbox, you can use the dataset objects to represent data with column and row names. If not, you can use cell arrays to represent row/column names, but indexing would be harder. For example,

M = {'', 'c1', 'c2', 'c3'; 'r1', 1, 2, 3; 'r2', 5, 6, 7; 'r3', 2, 4, 5}

If you want to mix strings and numerical values in the same data container (variable), using cell arrays is the most common way. However, I would try to keep these separate. For example, you could have:

colNames = {'c1', 'c2', 'c3'}
rowNames = {'r1', 'r2', 'r3'}
data = rand(3,3) % A random matrix with 3 rows and 3 columns.

And if you want to plot a data point given, say, 'c1' and 'r3', you could code

i = find(strcmp(rowNames, 'r3')) % Row index
j = find(strcmp(colNames, 'c1')) % Column index
plot3(i, j, data(i,j)) % Plot the data at 'c1' and 'r3' location

But again, this is also a somewhat convoluted way of working with numerical data. Plotting based on row/column names, rather than row/column indices is harder.

By the way, plot(x,y,z) is not a valid command. For 3D plotting of curves, you should use the plot3 command.

Share:
10,149

Related videos on Youtube

Siato
Author by

Siato

Updated on June 04, 2022

Comments

  • Siato
    Siato over 1 year

    I am a newbie in Matlab, so I would appreciate your help! I have some data that looks like this:

         word1 word2 word3 word4 word5
    word1 1.2   3.5   4.1   2.1   3.6
    word2 5.1   4.2   3.7   6.3   5.9
    word3 8.3   4.6   5.5   9.1   5.3
    word4 7.1   8.2   2.1   1.7   4.3
    word5 2.4   2.5   3.2   6.8   9.2
    

    and I want to create a 3D graph where x is the columns dimension, y is the rows dimension and z is the numbers in the matrix. I would like to use plot(x, y, z) and pcolor(x, y, z).

    How can I construct this in Matlab? Can I create a numerical matrix and somehow attach headers to it? Do I need a cell matrix?

    PS: I need the words because I want to be able to retrieve them when I index to a particular location.

    Thank you in advance!

  • EBH
    EBH over 7 years
    @Thea It is now better to use the table object, since MathWorks taking dataset out