无许可证
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.
引用格式
Gerald Dalley (2024). parseEnum (https://www.mathworks.com/matlabcentral/fileexchange/10007-parseenum), MATLAB Central File Exchange. 检索时间: .
MATLAB 版本兼容性
平台兼容性
Windows macOS Linux类别
标签
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!版本 | 已发布 | 发行说明 | |
---|---|---|---|
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. |