You set 9 colors in your colormap but you only have 6 unique intergers in "A". That means you're asking matlab to distribute 9 colors evenly across 6 values. To make see the mapping, add a colorbar to your plot and set the y axis ticks of the colorbar to intergers (see below).
cb = colorbar();
set(cb,'YTick', 1:9)
If you want a 1:1 mapping you've got 2 opitions.
Option 1: number of colors = range of values
You've got 6 unique integer values (see below) then you must have only 6 colors in your colormap.
unique(A(:))
ans =
0
1
2
3
4
5
Here's your code with only the first 6 colors and with a colorbar.
A=[1:3;2:4;3:5;0 0 0];
cmap = [0 0.5 0.5;
0.75 0.75 0;
1 0.75 0.25;
0.25 0 1;
1 1 0.75;
0.75 0 0.75];
colormap(cmap);
imagesc(A);
cb = colorbar();
set(cb,'YTick', 0:5)
Option 2: control color range with caxis()
The range of integer values in your data is 6 but you've assigned 9 colors. If you want to scale the colors such that only the first 6 colors are used and the last 3 ignored, set the caxis() range from 0:9 instead of 0:5.
A=[1:3;2:4;3:5;0 0 0];
cmap = [0 0.5 0.5;0.75 0.75 0;1 0.75 0.25;
0.25 0 1;1 1 0.75;0.75 0 0.75;
0.75 0.75 0;0.25 0.25 0.25;1 0.5 0];
imagesc(A);
colorbar()
colormap(cmap);
caxis([0 9]);
Best Answer