In switch-case, case values from variable (dynamic)

4 vues (au cours des 30 derniers jours)
Pramit Biswas
Pramit Biswas le 31 Mai 2018
Commenté : Stephen23 le 1 Juin 2018
array1 = [1 2 3]; % this will change in the program
array2 = [4 5 6]; % this will change in the program
switch anyVariable
case {array1}
disp('1')
case {array2}
disp('2')
otherwise
disp('3')
end
This always displays 3, irrespective of the value of anyVariable. Shall I change it to if-elseif kind structure?

Réponse acceptée

Stephen23
Stephen23 le 31 Mai 2018
Modifié(e) : Stephen23 le 31 Mai 2018
Use cell arrays, where each cell contains one scalar numeric (or a char vector):
V1 = {1,2,3};
V2 = {4,5,6};
switch scalarVal
case V1
disp('one')
case V2
disp('two')
otherwise
disp('none')
end
  7 commentaires
Pramit Biswas
Pramit Biswas le 1 Juin 2018
Only after viewing the comment I tried to execute that (Thanks for the comment). It can be a nice feature to add.
Stephen23
Stephen23 le 1 Juin 2018
@Pramit Biswas: you can convert numeric row vectors to char (as long as they are suitable, i.e. positive integers, etc).

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by