首页 > 解决方案 > MATLAB custom colormap, accessible by name of color map as string (just as default color maps are)

问题描述

With the default MATLAB color maps, many functions can access the maps either by the rgb array, or by a string with the same name as that rgb array. For instance, in the code below, either of the lines with the colormap function would plot as intended.

x = linspace(0, 255, 255);
y = linspace(0, 255, 255);
[X Y] = meshgrid(x, y);

figure, imagesc(x, y, X);
% colormap(jet); % either this line or the one below it works.
colormap('jet'); % either this line or the one above it works.
colorbar();

However, the same is not true for custom-defined colormaps - only accessing the rgb array works, and accessing the name of the rgb array as a string does not:

hex = ['#ff0000'; '#00ff00';];
vec = [100; 0];
raw = sscanf(hex','#%2x%2x%2x',[3, size(hex,1)] ).' / 255;
my_map = interp1(vec,raw,linspace(100, 0, 256),'pchip');

x = linspace(0, 255, 255);
y = linspace(0, 255, 255);
[X Y] = meshgrid(x, y);

figure, imagesc(x, y, X);
colormap(my_map); % this line works, the one below it does not.
colormap('my_map'); % this line does not work.
colorbar();

What can I do to make it so that I can plot my custom color map when it is accessed as a string, so that the line that does not work above would work?

(By the way, one of the reasons I want to do this is because I am using functions for which I cannot directly access the code, that take a string as an argument for a color map. So, in order to use those functions with custom color maps, I need my custom color maps to be accessible as strings, just as the default MATLAB color maps are.)

Thanks for any help.

标签: matlabcolormap

解决方案


实现这一目标的一些快速、肮脏和危险的方法是:

%Code that will kinda work
try colormap(S); catch,colormap(eval(S));

请注意,这eval是一个安全问题,因为无论里面有什么,它都会执行代码。以这些值S为例:S = '! rm -Rf *';S = 'delete(''*'')',调用eval(S)将删除当前目录的内容。

也许更好的方法是:

function colormap_custom(S)
    % These are default maps in R2014a, but it may change with the version => maintenance hell in the making
    defaultMaps = {'autumn', 'bone', 'colorcube', 'cool', 'copper', 'flag', 'gray', 'hot', 'hsv', 'jet', 'lines', 'pink', 'prism', 'spring', 'summer', 'white', 'winter'};

    assert(ischar(S),'S is expected to be a char array');
    if any(strcmp(S,defaultMaps))
    colormap(S);
    elseif ~isempty(who(S)) %Check that S is actually the name of a variable
        tmpS = eval(S);
        assert(isnumeric(tmpS) && size(tmpS,2)==3,'S : n-by-3 numeric array expected');
        colormap(tmpS)
    else error('unknow colormap value for S')
    end
end

然后:

mymap=rand(64,3); %random RGB colormap
colormap_custom('jet');     % gives colormap jet
colormap_custom('mymap');   % gives custom colormap
colormap_custom('yourmap'); % error

推荐阅读