function val = parseEnum(myStr, varargin)
%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.
%
%by Gerald Dalley
if (mod(length(varargin),2) ~= 0)
error('String-value pairs must be supplied.');
end
matches = find(strcmp({varargin{1:2:end}}, myStr));
if (length(matches) == 0),
val = [];
else
val = varargin{(matches(1))*2};
end