How do I check if a value is a correct color?
Show older comments
Whether there is a function like
logical = isvalidcolor(value)
Accepted Answer
More Answers (2)
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.
6 Comments
Image Analyst
on 6 Dec 2015
I'd add as the first line
color = lower(color);
It will make it more robust by handling upper case characters and words also.
Tommy
on 6 Dec 2015
Thanks! I adapted it.
Rick Coon
on 3 Apr 2019
Actually, doesn't using strcmpi eliminate the need to use color = lower(color); ?
Image Analyst
on 3 Apr 2019
Yes. Maybe he adapted that part also after my comment.
Grzegorz Lippe
on 26 Apr 2021
Well that helps until that point somebody specifies the color as hexadecimal value or integer from 0 ...255. Hope mathworks creates a validate color function :/
Paul Wintz
on 20 Aug 2021
Paul Wintz
on 20 Aug 2021
2 votes
Categories
Find more on Whos 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!