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

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.)

 Respuesta aceptada

Image Analyst
Image Analyst el 16 de Jul. de 2014

1 voto

Not that I'm aware of - there's just not that much need - though you could write one if you want.

4 comentarios

Ivan
Ivan el 17 de Jul. de 2014
Thanks a lot!
But I have hoped I will not write this ))
Image Analyst
Image Analyst el 17 de Jul. de 2014
If it's not 'r', 'b', and so on, what will you do? Announce an error? Well whatever function you'd pass the "bad" color code into will announce an error also, so why do you need to do it also?
Ivan
Ivan el 30 de Jul. de 2014
It's a good question! I havn't known about announcing an error by uicontrol or some else.
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;

Iniciar sesión para comentar.

Más respuestas (2)

Tommy
Tommy el 6 de Dic. de 2015
Editada: Tommy el 6 de Dic. de 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.

6 comentarios

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
Tommy el 6 de Dic. de 2015
Thanks! I adapted it.
Rick Coon
Rick Coon el 3 de Abr. de 2019
Actually, doesn't using strcmpi eliminate the need to use color = lower(color); ?
Image Analyst
Image Analyst el 3 de Abr. de 2019
Yes. Maybe he adapted that part also after my comment.
Grzegorz Lippe
Grzegorz Lippe el 26 de Abr. de 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
Paul Wintz el 20 de Ag. de 2021
Matlab 2020b has a validatecolor function.

Iniciar sesión para comentar.

Paul Wintz
Paul Wintz el 20 de Ag. de 2021

2 votos

In Matlab 2020b and later, use the validatecolor function.

Preguntada:

el 16 de Jul. de 2014

Respondida:

el 20 de Ag. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by