Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A script for creating color maps with multiple gradients.
% [INPUT]
% c1 = A vector of three floats [0,1] representing the first RGB color.
% c2 = A vector of three floats [0,1] representing the second RGB color.
% c3 = A vector of three floats [0,1] representing the third RGB color.
% n1 = An integer [0,512] representing the span of the first gradient (c1 and c2).
% n2 = An integer [0,512] representing the span of the second gradient (c2 and c3).
%
% [OUTPUT]
% cmap = An (n1+n2)-by-3 matrix of floats representing the colormap.
% [NOTES]
% Setting n1 or n2 to 0 produces a colormap with a single gradient.
function cmap = create_colormap(varargin)
persistent p;
if (isempty(p))
p = inputParser();
p.addRequired('c1',@(x)validateattributes(x,{'double','single'},{'vector','numel',3,'real','finite','>=',0,'<=',1}));
p.addRequired('c2',@(x)validateattributes(x,{'double','single'},{'vector','numel',3,'real','finite','>=',0,'<=',1}));
p.addRequired('c3',@(x)validateattributes(x,{'double','single'},{'vector','numel',3,'real','finite','>=',0,'<=',1}));
p.addRequired('n1',@(x)validateattributes(x,{'numeric'},{'scalar','integer','real','finite','>=',0,'<=',512}));
p.addRequired('n2',@(x)validateattributes(x,{'numeric'},{'scalar','integer','real','finite','>=',0,'<=',512}));
end
p.parse(varargin{:});
res = p.Results;
cmap = create_colormap_internal(res.c1,res.c2,res.c3,res.n1,res.n2);
end
function cmap = create_colormap_internal(c1,c2,c3,n1,n2)
c2_r = c2(1);
c2_g = c2(2);
c2_b = c2(3);
cmap = [linspace(c1(1),c2_r,n1); linspace(c1(2),c2_g,n1); linspace(c1(3),c2_b,n1)];
cmap(:,end+1:end+n2) = [linspace(c2_r,c3(1),n2); linspace(c2_g,c3(2),n2); linspace(c2_b,c3(3),n2)];
cmap = cmap';
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment