File Exchange

image thumbnail


version (1.72 KB) by Kenneth Eaton
Converts a string representation of a color to an RGB triple


Updated 03 Apr 2008

View License

A simple utility to convert a ColorSpec value, represented as a string, to a numeric RGB triple. This function does not use eval. One possible use is for reading a user-entered color value from an editable text box.

str2rgb('yellow') returns [1 1 0]
str2rgb('y') returns [1 1 0]
str2rgb('[1 1 0]') returns [1 1 0]
str2rgb('1 1 0') returns [1 1 0]
str2rgb('[1; 1; 0]') returns [1 1 0]
str2rgb('[0 0.5 0.91]') returns [0 0.5000 0.9100]
str2rgb('purple') returns NaN
str2rgb('[1 2]') returns NaN

Cite As

Kenneth Eaton (2020). str2rgb (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (7)

V. Poor

alain boyer

Kenneth Eaton

Jos, the driving force behind me creating this function was for reading a user input for a color from an editable text box. In this case, the 'String' argument from the text box could be something like 'r g b', and I wanted to allow this as a valid way for the user to define a color in the text box.

Jos (see profile)

Kenneth, I understand your efforts using regexp. However, I do no see why anybody should use your function to change the string 'r g b' into the numerical vector [r g b]
If time permits, I will put my alternative on the FEX. Regards, Jos

Kenneth Eaton

Jos x,
Actually, the code you suggested wouldn't work for the case when colorstr = '[1 0 0]'. It would throw an error and return NaN. STR2RGB will allow a string representation of an RGB triple like '[1 0 0]' or '1 0 0'. Thanks for the comment, though.

Kenneth Eaton

The alternative you suggested will work, but I wanted to solve it using regexp instead of having to create any new graphics objects.

Jos x@y.z

Why not let Matlab handle this?

function rgb = getrgb(colorstr)
fh = figure('visible','off') ;
ph = plot(1) ;
set(ph,'color',colorstr) ;
rgb = get(ph,'color') ;
rgb = [NaN NaN NaN] ;
% End of function ====

MATLAB Release Compatibility
Created with R14SP3
Compatible with any release
Platform Compatibility
Windows macOS Linux