Code covered by the BSD License  

Highlights from
str2rgb

5.0

5.0 | 2 ratings Rate this file 2 Downloads (last 30 days) File Size: 1.72 KB File ID: #19432

str2rgb

by Kenneth Eaton

 

02 Apr 2008 (Updated 03 Apr 2008)

Converts a string representation of a color to an RGB triple

| Watch this File

File Information
Description

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.

Examples:
   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

Acknowledgements
This submission has inspired the following:
GETRGB (v1.0)
MATLAB release MATLAB 7.1.0 (R14SP3)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (7)
03 Apr 2008 Jos x@y.z

Why not let Matlab handle this?
   
function rgb = getrgb(colorstr)
fh = figure('visible','off') ;
ph = plot(1) ;
try
    set(ph,'color',colorstr) ;
    rgb = get(ph,'color') ;
catch
    rgb = [NaN NaN NaN] ;
end
delete(fh)
% End of function ====

03 Apr 2008 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.

03 Apr 2008 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.

04 Apr 2008 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

04 Apr 2008 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.

19 Dec 2008 alain boyer  
19 Dec 2008 V. Poor  
Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
strings Kenneth Eaton 22 Oct 2008 09:56:16
string color colorspec rgb Kenneth Eaton 22 Oct 2008 09:56:16

Contact us at files@mathworks.com