用颜色绘制矩阵

Draw matrix with colours

我正在做一个大学项目,我需要在图表中绘制矩阵的单元格并根据其值用颜色填充它们,但我在颜色矩阵方面遇到了很多麻烦,因为我无法将其用作填充函数的输入。

我的想法是得到类似于下图的东西,但我在代码的坐标中添加了限制。

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)

输入矩阵为:

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

我收到这个错误:

Error using fill
Error in color/linetype argument.

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

正如您提到的,您希望 1 为蓝色,0 为黄色,这与 imagesc 默认情况下的做法相反。因此,您需要反转 Table 矩阵中的值并将其提供给 imagesc 函数。

imagesc(~Table)

(代题主发帖移动到答案部分).

感谢 Sardar Usama,我能够找到问题的解决方案。这是代码:

function [ output_args ] = drawMatrix(Table)
colors = [1,1,1;0,0,0]; %RGB colors to use 
%(2 in my case,because only has 2 possible values).
values = [0,1]; %The 2 possible values.
imagesc(Table,values); %Creates an image with the matrix Table and the 
range of values.
colormap(colors); %
axis off;