Get current colormap used on i.e. surfaceplot as string

10 views (last 30 days)
Is there any way that I can get the current colormap of i.e. a surface plot returned as a string?
If I have a plot, e.g.
x = -3:0.1:3;
y = -3:0.1:3;
[X Y] = meshgrid(x,y);
R = sqrt(X.^2+Y.^2);
Z = abs(cos(sinc(R)).^X);
h = surf(X,Y,Z);
colormap('cool');
I can get access to the current colormap through
cm = get(gcf,'Colormap');
which is represented as a 64-by-3) double array. However, I'd like to get the name of the colormap used returned as a string (i.e. s = 'cool'); is there any way to do this - so I later on can use this string in a strcmpi() check?
best regards, dm

Accepted Answer

Walter Roberson
Walter Roberson on 8 May 2011
You could figure out the number of entries in the current colormap, and then loop through all the named colormaps, invoking them to return a map of the appropriate size, and then using isequal() to compare the two. For this purpose keep in mind that colormap names are actually functions that, when invoked, return an Mx3 matrix of values.
For example,
nent = size(cm,1);
cmaps = {@cool, @hot, @copper, @flag};
for K = 1:length(cmaps)
cmap = cmaps{K}(nent);
if isequal(cm, cmap)
%found a map
break
end
end
You will have the problem that any Mx3 of the appropriate class and data range can be a colormap: colormaps are not restricted to the named ones.
If you were hoping that MATLAB remembered the name of the colormap in use... sorry, it doesn't do that.
  1 Comment
dm
dm on 9 May 2011
Thanks for the answer. I was indeed hoping MATLAB would remember the name of the colormap in use, so things would turn out easier in my script, but it isn't a big issue. I already use something similar to your hack, but I have to say yours is much more elegant - so I might have to steal your piece of code and put a thanks to in file! ;)

Sign in to comment.

More Answers (0)

Categories

Find more on Colormaps in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!