parseEnum
1.3K Downloads
Updated 21 Feb 2006
No License
val = parseEnum(myStr, str1,val1, str2,val2, ..., strn,valn)
Takes MYSTR and searches for the STRI string that matches it. Returns the corresponding VALI. Returns an empty array if not match is found. Uses STRCMP to do the matching.
Examples:
parseEnum('foo', 'foo',1, 'bar',2) --> 1
parseEnum('bar', 'foo',1, 'bar',2) --> 2
parseEnum('baz', 'foo',1, 'bar',2) --> []
Motiving scenario:
This function was written to clean up and compact code where I wanted to look up a mapping from a string to a value. For example, before I might have had someting like the following (using Matlab 7 FIND enhancements)
function code = getFruitCode(fruit)
names = {'apple', 'orange', 'banana'};
values = [-1 0 1];
code = values(find(strcmp(names, fruit), 1));
and with PARSEENUM, we can condense it down to
function code = getFruitCode(fruit)
code = parseEnum(fruit, 'apple',-1, 'orange',0, 'banana',1);
Changes:
2006-02-18: Uses faster STRCMP implementation as suggested by Duane Hanselman. Removed boilerplate copyright. Returns an empty array instead of generating an error when no match is found. Added a motivating scenario to docs.
Cite As
Gerald Dalley (2023). parseEnum (https://www.mathworks.com/matlabcentral/fileexchange/10007-parseenum), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform Compatibility
Windows macOS LinuxCategories
Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
Version | Published | Release Notes | |
---|---|---|---|
1.0.0.0 | Removed boilerplate copyright, removed loop as per Duane Hanselman's suggestion, and added a motivating scenario to the docs. Added a post-hoc "inspired by" link to PARSEARGS that tackles a related problem. |