MATLAB: Specific values in colorbar

colorbarcolormap

I am trying to plot a heatmap as the following:
data = [2 1 0 0 0 0 0 0 0 0;1 2 15 0 0 0 0 0 0 0];
colormap('hot');
imagesc(data);
colorbar;
But I want a colorbar with only the values in my data. I don't really need the "transitioning" ones. Is there a way to do so?
Thanks!

Best Answer

The unique values in you original question are [0 1 2 15]. Do you want just those to appear in the colorbar, or all possible integers between 0 and 15?
For the former:
data = [2 1 0 0 0 0 0 0 0 0;1 2 15 0 0 0 0 0 0 0];
[unq, ~, iunq] = unique(data);
iunq = reshape(iunq, size(data));
ncol = length(unq);
cmap = hot(ncol*2);
cmap = cmap(1:2:end,:);
imagesc(iunq);
colormap(cmap);
cb = colorbar;
set(gca, 'clim', [0.5 ncol+0.5]);
set(cb, 'ticks', 1:ncol, 'ticklabels', cellstr(num2str(unq)));
Walter's code covers the latter case. As a side note, I'd usually just suggest hot(4) to get the 4-color hot colormap, but interpolating hot to only 4 colors results in two nearly-identical shades of yellow; hence the doubling of colors and then using every other in my cmap generation above.