Search code examples
matlabmatrixmatlab-figure

Draw matrix with colours


I'm working on a college project where I need to draw in a graph the cells of a matrix and fill them with a color depending on its value, but I'm having lots of trouble with the color matrix because I am not able to use it as input of the fill function.

The idea is to get something similar to the image below but with the limitations I add in the coordinates of my code.

expected result

function [ output_args ] = drawMatrix(Table)

[m,n]=size(Table); %Get the size of the matrix;
X = 1-0.5:1:n+0.5; %Array with the X coordinates of each cell. 
Y = 1-0.5:1:m+0.5; %Array with the Y coordinates of each cell.
C = repmat('w',[m,n]); %Color matrix to represent the color of each single cell, originally all in white.
[x,y]=meshgrid(X,Y); %Creates the coordinates of the cells of the matrix.
for a=1:m
    for b=1:n
        if Table (a,b) == 1 
            C(a,b)='b'; % If the value of the original cell is 1, the color is changed to blue.
        end
    end
end
photo = fill(x', y', C)

The input matrix is:

[0, 0, 1, 1, 0;
 0, 1, 1, 0, 0;
 0, 0, 1, 0, 0;
 1, 0, 0, 0, 0]

I am getting this error:

Error using fill
Error in color/linetype argument.

Error in drawMatrix (line 20)
photo = fill(x', y', C);


Solution

  • As you have mentioned that you want blue color for ones and yellow color for zeros, this is the opposite of what imagesc does by default. So, you need to invert the values in the Table matrix and give it to the imagesc function.

    imagesc(~Table)
    

    output