Search code examples
matlabmatrixgraphics

Matlab color-coded plot of matrix


Say I have a matrix like

A= [0 -50 2;
    0 -18 7;
    0  13 3;
    1 -50 3;
    1 -18 5;
    1  13 1;]

In reality, this matrix is larger but the first column is counting upwards while the second one is repetitive. Now I want to plot this colour-coded to get a result like e.g. this one, i.e. A(:,1) and A(:,2) are the x and y axes, respectively.

How would you do that? I've tried pcolor, imagesc and others but no luck so far. Sorry if this is a duplicate - I have searched stackoverflow and other websites but did not find anything that I could use.


Solution

  • The following code works even if the grid defined by the x and y columns has missing or repeated entries. In the first case the result will contain no colour for the missing values (just the axis background), and in the second case the values will be overwritten.

    The code generates a matrix from the data where the missing entries are marked with NaN, and then displays it using pcolor, which ignores NaN entries. Because of how this function works, a column and a row need to be added to the matrix before displaying.

    A = [0 -50 2;
         0 -18 7;
         0  13 3;
         1 -50 3;
         1 -50 5; 
         1  13 1] % example. Entry (1,-50) is repeated, and entry (1,-18) is missing
    [ux, ~, ind_x] = unique(A(:,1)); % unique values of x and indices to them
    [uy, ~, ind_y] = unique(A(:,2)); % same for y
    B = NaN(numel(uy), numel(ux)); % row is y, column is x
    B(ind_y + size(B,1)*(ind_x-1)) = A(:,3); % linear indexing to fill the values into B
    pcolor([B NaN(size(B,1),1); NaN(1,size(B,2)+1)]) % pcolor discards last row and column
    axis xy
    xticks((1:numel(ux))+0.5), xticklabels(ux)
    yticks((1:numel(uy))+0.5), yticklabels(uy)
    colorbar
    

    enter image description here