Wildcard or multiple conditions on switch/case?
Show older comments
Hello,
Is there a way to deal with multiple conditions in switch/case? For example (this is just example):
- Meat could be chicken pork beef lamb
- Veggie could be beans peas corn
- Fruit could be apple pear blueberry
Looking for a way to then select for each possible combination. Is the easiest way just nested switch/case? Or is there something more elegant? Is there an easy way to use case wildcards (not great for this example)?
Thanks!
Doug
4 Comments
Walter Roberson
on 24 Apr 2018
Select for each possible combination? Do you mean something like recognizing that a given cell array includes one entry from each of the three categories? Or do you mean enumerating all of the valid combinations ?
Douglas Anderson
on 24 Apr 2018
Douglas Anderson
on 24 Apr 2018
Edited: Douglas Anderson
on 24 Apr 2018
Accepted Answer
More Answers (1)
Fangjun Jiang
on 24 Apr 2018
Choice='chicken';
switch Choice
case {'chicken','pork','beef'}
disp('meat');
case {'bean','pea'}
disp('veggie')
case {'apple','pear'}
disp('fruit');
otherwise
disp('no category');
end
7 Comments
Douglas Anderson
on 24 Apr 2018
David Walwark
on 18 Oct 2019
Edited: David Walwark
on 23 Oct 2019
Was helpful for trying to find out how to make a switch-case handle what I would normally assume I can use an 'OR' bar for.
So this is not really an answer to this question, but google lead me here to answer the question I had, so I am doing my part for the SEO by reinforcing it with more keywords.
The snarky question I had would be 'Why can't I use OR statements in a switch case?'. I really just wanted the switch case to be case insensitive by including some of the possibilities I knew would come up in my spectroscopic context: 'energy','eV','ev','EV'...
Walter Roberson
on 18 Oct 2019
switch(lower(VARIABLE))
and then you do not have to worry about supplying 'eV' separate from 'ev' and so on.
David Walwark
on 23 Oct 2019
Thank you for this helpful tip.
Vivek Thaminni Ramamoorthy
on 7 May 2022
This should be the accepted answer. It is a more elegant way to combine multiple cases.
Shawn Stone
on 4 Aug 2022
For those wanting more robust and elegant ways of matching text, look up the validatestring() function: https://www.mathworks.com/help/matlab/ref/validatestring.html So that you don't have to supply all possible spellings of different text cases.
Categories
Find more on App Building in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!