Wildcard or multiple conditions on switch/case?
이전 댓글 표시
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
Walter Roberson
2018년 4월 24일
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
2018년 4월 24일
Douglas Anderson
2018년 4월 24일
편집: Douglas Anderson
2018년 4월 24일
채택된 답변
추가 답변 (1개)
Fangjun Jiang
2018년 4월 24일
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
Douglas Anderson
2018년 4월 24일
David Walwark
2019년 10월 18일
편집: David Walwark
2019년 10월 23일
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
2019년 10월 18일
switch(lower(VARIABLE))
and then you do not have to worry about supplying 'eV' separate from 'ev' and so on.
David Walwark
2019년 10월 23일
Thank you for this helpful tip.
Vivek Thaminni Ramamoorthy
2022년 5월 7일
This should be the accepted answer. It is a more elegant way to combine multiple cases.
Shawn Stone
2022년 8월 4일
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.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!