Looks up values associated with a given string.
1,3K download
Aggiornato 21 feb 2006

Nessuna licenza

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.

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


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.

Cita come

Gerald Dalley (2024). parseEnum (, MATLAB Central File Exchange. Recuperato .

Compatibilità della release di MATLAB
Creato con R14SP2
Compatibile con qualsiasi release
Compatibilità della piattaforma
Windows macOS Linux
Scopri di più su String Parsing in Help Center e MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Versione Pubblicato Note della release

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.