A switch case with multiple results or switch expressions?

73 vues (au cours des 30 derniers jours)
Rishi Balasubramanian
Rishi Balasubramanian le 23 Déc 2020
Commenté : Walter Roberson le 23 Déc 2020
Is such a switch case possible? If not, whats my workaround for it?
switch r,d
case d=1 && r=1
continue
case d=1 && r>1
disp('zero')
case d=0 && r=1
disp('positive one')
case d=0 && r>1
disp('other value')
end

Réponse acceptée

Cris LaPierre
Cris LaPierre le 23 Déc 2020
First we need to fix some syntax issues.
  • A CONTINUE may only be used within a FOR or WHILE loop
  • Logical comparison requires 2 equals: d==1 && r>1
One way to swtich based on the value of multiple variables is this:
r = 1;
d = 0;
switch true
case d==1 && r>1
disp('zero')
case d==0 && r==1
disp('positive one')
case d==0 && r>1
disp('other value')
end
positive one
  1 commentaire
Walter Roberson
Walter Roberson le 23 Déc 2020
It is true that a continue can only be used within for or while, but we could speculate that this switch logic is indeed inside a loop.

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 23 Déc 2020
switch true
case d==1 && r==1
continue
case d==1 && r>1
disp('zero')
case d==0 && r==1
disp('positive one')
case d==0 && r>1
disp('other value')
otherwise
disp('Uh-oh!')
end

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by