1
votes

I have random matrix with arbitrary dimensions and I want to assign a color for each value (randomly or not) and plot the matrix with numbers like,

enter image description here

So far I've done this,

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

which gives me this,

enter image description here

for

 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

but as you can see I've lost first row and last column of A.

Actually the problem starts bu using pcolor, which gives an (m-1)x(n-1) plot for mxn input.

Any suggestions?

Thanks,

2
@AnonSubmitter85, yes, but if I don't use them the lost row and column will be written out side of the plot.Rashid
Yeah, I noticed that when I ran the code. If you look at the help section, you'll see that "In the default shading mode, 'faceted', each cell has a constant color and the last row and column of C are not used."AnonSubmitter85
@AnonSubmitter85, That was interesting!Rashid

2 Answers

3
votes

Using imagesc instead of pcolor solves the problem. It also brings some other benefits:

  • Avoids the need for flipud;
  • The coordinates of the text objects become integer values;
  • Axes are automatically set to "matrix" mode, with the origin in the upper right corner.

Code:

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

For

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

this produces

enter image description here

2
votes

I just padded the matrix prior to pcolor and I think it's the effect you wanted. The reason it works comes from the help doc for pcolor, which states that

In the default shading mode, 'faceted', each cell has a constant color and the last row and column of C are not used.

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