绘制矩阵,将值作为颜色绘制

时间:2014-11-02 22:17:22

标签: matlab matrix plot

我有任意尺寸的随机矩阵,我想为每个值(随机或不随机)分配颜色,并用数字绘制矩阵,

enter image description here

到目前为止,我已经完成了这项工作,

m = 12;
n = 8;
A = randi(5,[m n]);
Arot = flipud(A);
pcolor(Arot);figure(gcf);
for i = 1 : n -1
    for j = 1 : m -1
        text(i + .5 , j + .5 ,num2str(Arot(j,i)),'FontSize',18);
    end
end

给了我这个,

enter image description here

代表

 A =

 4     4     4     1     2     1     4     2
 5     2     2     3     2     1     1     2
 1     2     1     4     1     2     5     5
 1     3     5     3     1     4     1     3
 3     4     4     4     3     3     3     4
 2     5     2     2     1     1     2     4
 1     3     1     3     5     5     2     4
 5     1     2     4     1     4     1     2
 2     4     5     5     1     3     5     2
 4     2     2     3     4     3     3     4
 3     5     3     2     4     3     3     1
 1     4     5     3     2     4     3     5

但正如您所见,我已经丢失了A的第一行和最后一列。

实际上问题是使用pcolor启动,这为(m-1)x(n-1)输入提供了mxn图。

有什么建议吗?

谢谢,

2 个答案:

答案 0 :(得分:3)

使用imagesc代替pcolor可以解决问题。它还带来了一些其他好处:

  • 避免使用flipud;
  • text个对象的坐标变为整数值;
  • 轴自动设置为“矩阵”模式,原点位于右上角。

代码:

m = 8;
n = 6;
A = randi(5,[m n]);
imagesc(A);
for ii = 1:n
    for jj = 1:m
        text(ii, jj, num2str(A(jj,ii)), 'FontSize', 18);
    end
end

有关

A =
     4     5     4     2     4     4
     5     4     3     4     4     2
     5     4     1     1     1     3
     4     3     5     2     5     4
     1     2     2     2     5     3
     1     5     2     5     1     3
     4     3     1     3     3     1
     3     1     2     4     2     3

这会产生

enter image description here

答案 1 :(得分:2)

我只是在pcolor之前填充了矩阵,我认为这是你想要的效果。它起作用的原因来自pcolor的帮助文档,其中说明了

  

在默认着色模式中,'刻面',每个单元格都有一个恒定的颜色   并且不使用C的最后一行和一列。

m = 12;
n = 8;
A = randi(5,[m n]);
Arot = flipud(A);
Arot = [ Arot; Arot(end,:) ];
Arot = [ Arot, Arot(:,end) ];
pcolor(Arot);figure(gcf);
for i = 1 : n
  for j = 1 : m
    text(i + .5 , j + .5 ,num2str(Arot(j,i)),'FontSize',18);
  end
end