Wildcard or multiple conditions on switch/case?
Mostrar comentarios más antiguos
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 comentarios
Walter Roberson
el 24 de Abr. de 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
el 24 de Abr. de 2018
Douglas Anderson
el 24 de Abr. de 2018
Editada: Douglas Anderson
el 24 de Abr. de 2018
Respuesta aceptada
Más respuestas (1)
Fangjun Jiang
el 24 de Abr. de 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 comentarios
Douglas Anderson
el 24 de Abr. de 2018
David Walwark
el 18 de Oct. de 2019
Editada: David Walwark
el 23 de Oct. de 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
el 18 de Oct. de 2019
switch(lower(VARIABLE))
and then you do not have to worry about supplying 'eV' separate from 'ev' and so on.
David Walwark
el 23 de Oct. de 2019
Thank you for this helpful tip.
Vivek Thaminni Ramamoorthy
el 7 de Mayo de 2022
This should be the accepted answer. It is a more elegant way to combine multiple cases.
Shawn Stone
el 4 de Ag. de 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.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!