MATLAB: Finding rbg color values from color map

colormapcolourgraphingMATLABplot3

Lets say I have defined a color map to range from 0 to 10.
figure
c=colorbar;
set(c, 'ylim', [min(0) max(10)])
caxis([min(0) max(10)])
And plot 5 lines that have a scalar value associated with it such that:
scalar = [0; 7; 4; 10; 2]
I would like to find code that matches the value of the scalar to the appropriate colour in the colorbar such that:
scalar_colour = [RBG of scalar(1); RBG of scalar(2); RBG of scalar(3) ...]
Any help would be very much appreciated. The desired solution would replace the colours in the graph with the following:
  • one = dark blue (0)
  • two = yellow/green (7)
  • three = light blue (4)
  • four = yellow (10)
  • five = blue (2)

Best Answer

All you need to do is interpolate your values according to your caxis and colormap, bearing in mind that value outside the caxis range are clamped to that range:
scalar = [0; 7; 4; 10; 2]
climits = caxis;
cmap = colormap;
scalarclamped = scalar;
scalarclamped(scalar < climits(1)) = climits(1);
scalarclamped(scalar > climits(2)) = climits(2);
rgb = interp1(linspace(climits(1), climits(2), size(cmap, 1)), ...
cmap, ...
scalarclamped)