Wildcard or multiple conditions on switch/case?
160 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Douglas Anderson
el 24 de Abr. de 2018
Comentada: Shawn Stone
el 4 de Ag. de 2022
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
Douglas Anderson
el 24 de Abr. de 2018
Editada: Douglas Anderson
el 24 de Abr. de 2018
Respuesta aceptada
Steven Lord
el 18 de Oct. de 2019
I'm not sure how switch / case fits into this. You don't need it (unless this is part of a homework assignment and it requires you to use a switch / case.) Let's define the food groups. I'm using string arrays but you could use numbers.
meat = ["chicken"; "beef"; "pork"; "lamb"];
veggie = ["beans"; "peas"; "corn"];
fruit = ["apple"; "pear"; "blueberry"];
Use ndgrid to generate the 3-D arrays where combining the same element of each of the three arrays gives you one combination.
[M, V, F] = ndgrid(meat, veggie, fruit);
Combine them into a 2-D list with each row representing one combination.
possibleDinners = [M(:), V(:), F(:)];
What to eat today?
whichDinner = randi(size(possibleDinners, 1));
dinnerTonight = possibleDinners(whichDinner, :)
3 comentarios
Walter Roberson
el 19 de Oct. de 2019
I am not sure how this deals with "I need to call three different functions, depending on the combination." ?
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
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.
Ver también
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!