Wildcard or multiple conditions on switch/case?
Afficher commentaires plus anciens
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 commentaires
Walter Roberson
le 24 Avr 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
le 24 Avr 2018
Douglas Anderson
le 24 Avr 2018
Modifié(e) : Douglas Anderson
le 24 Avr 2018
Réponse acceptée
Plus de réponses (1)
Fangjun Jiang
le 24 Avr 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 commentaires
Douglas Anderson
le 24 Avr 2018
David Walwark
le 18 Oct 2019
Modifié(e) : David Walwark
le 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
le 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
le 23 Oct 2019
Thank you for this helpful tip.
Vivek Thaminni Ramamoorthy
le 7 Mai 2022
This should be the accepted answer. It is a more elegant way to combine multiple cases.
Shawn Stone
le 4 Août 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.
Catégories
En savoir plus sur App Building dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!