MATLAB: Custom colormap with missing colors

colormapcustum colormapimage

If I create the following image, with 3 possible values: 1, 2 and 10.
im = zeros(128,128)
im(1:32,:) = 1
im(33:64,:) = 2
im(65:end,:) = 10
ax = imshow(im,[])
%I apply the following colormap:
cmap = [0.9020 0.0980 0.2941
0.2353 0.7059 0.2941
0.8000 0.8000 0.8000]
colormap(ax.Parent,cmap)
I obtain an image with only 2 colors, when the colormap has 3 colors. Why isn't the colormap being respected? I want these specific colors for each value of the image. And I want my colormap to include only these colors, no more and no less. And no, my image does not contain values from 3 to 9. It is just 1, 2 and 10 and it is supposed to be like this.
Any help appreciated
André

Best Answer

You could:
1. specify the limits, and provide the axes handle when calling colormap:
imshow(im,[1,3]);
colormap(gca,cmap)
2. treat it as an indexed image (note that out-of-range indices are truncated to the end colors):
>> imshow(im,cmap)
3. convert it to a TrueColor (RGB) image:
>> [~,idx] = ismember(im,[1,2,10]);
>> rgb = ind2rgb(idx,cmap);
>> imshow(rgb)