MATLAB: Does the colorbar inaccurately reflect the relationship between colors and function values when CDataMapping is set to direct

MATLAB

I have made a surface plot for a function with a maximum value of 10, and then I set the 'CDataMapping' property of the surface object to 'direct'. I turn the colorbar on, and the ticks of the colorbar say that the last color in the colormap represents 10. But on the plot, the value 10 is colored with the 10th color in the colormap. I would like the colorbar to be aware of the 'CDataMapping' setting, and adjust its tick mark labels automatically.

Best Answer

The ability for the colorbar to be aware of the axes' CDataMapping property is not available in MATLAB.
To work around this issue, the YTick and YTickLabel properties of the colorbar can be set manually based on the lenght of the colormap. Given a plot generated by the following code:
s = surf(peaks);
set(s,'CDataMapping','direct');
cb = colorbar('location','EastOutside');
The colorbar properties can be modified as follows:
ylimits = get(cb, 'YLim');
set(cb, 'YTick', linspace(ylimits(1), ylimits(2), 9));
set(cb, 'YTickLabel', {'< 0', '8', '16', '24', '32', '40', '48', '56', '> 64'});