# How do I check if a value is a correct color?

12 views (last 30 days)
Ivan on 16 Jul 2014
Answered: Paul Wintz on 20 Aug 2021
Whether there is a function like
logical = isvalidcolor(value)
to check if some value may be used like a color (one of values specified in ColorSpec e.g.)

Image Analyst on 16 Jul 2014
Not that I'm aware of - there's just not that much need - though you could write one if you want.
Image Analyst on 30 Jul 2014
You could do something like
message = sprintf('%s is an invalid color. Please use r, g, b, y, m, c, k, or w', theirColor);
uiwait(warndlg(message));
return;

Tommy on 6 Dec 2015
Edited: Tommy on 6 Dec 2015
Once I needed this function to suppress error messages, by setting wrong color values to MATLAB default. I used:
function logical_out = iscolor( color )
color = lower(color);
logical_out=(isnumeric(color) && (sum(size(color)==[1 3])==2 || ...
sum(size(color)==[3 1])==2) && sum((color<=[1 1 1] & ...
color>=[0 0 0]))==3) || sum(strcmpi({'y','m','c','r','g','b','w','k',...
'yellow','magenta','cyan','red','green','blue','white','black'},color))>0;
end
Hope this helps.
Paul Wintz on 20 Aug 2021
Matlab 2020b has a validatecolor function.

Paul Wintz on 20 Aug 2021
In Matlab 2020b and later, use the validatecolor function.