Mutually Exclusive Booleans in a single Switch
Mostra commenti meno recenti
Dear Matlab Commnunity
I have 4 mutually exclusive Boolean variables called "HH", "LH", "SO" and "CB". I wish an appropriate piece of code (concatenate string array for a plot legend) to run in the event any possible case is true. I currently have four separate 'if' statements;
legendtext = [];
if (HH == 1)
legendtext = [legendtext, {'Heavy Holes'}];
end
if (LH == 1)
legendtext = [legendtext, {'Light Holes'}];
end
if (SO == 1)
legendtext = [legendtext, {'Spin Orbit'}];
end
if (CB == 1)
legendtext = [legendtext, {'Electrons'}];
end
in the event of all four booleans being false (== 0) legendtext is an empty array, and in the event all four booleans are true (= 1) legendtext is a 1x4 cell.
I tried using a 'switch' statement since I was under the pretence that while 'if' statements jump to the end when the criteria is met, 'switch' statements go through all cases;
legendtext = [];
switch 1
case HH
legendtext = [legendtext, {'Heavy Holes'}];
case LH
legendtext = [legendtext, {'Light Holes'}];
case SO
legendtext = [legendtext, {'Spin Orbit'}];
case CB
legendtext = [legendtext, {'Electrons'}];
end
however I learned that unlike in C, matlab terminates when a case is matched!
So my question is: is there a way of getting the switch (or any other) statement to scan each mutually exclusive Boolean without using 4 separate if statements? (like a continue statement in a while loop)
4 Commenti
Sean de Wolski
il 21 Mar 2011
What's wrong with 4 if-statements?
Doug Hull
il 21 Mar 2011
If they are mutually exclusive, how can they all four be true as you stated?
Robert Ward
il 21 Mar 2011
Andrew Newell
il 21 Mar 2011
I agree with @Sean de - if statements seem like the simplest choice for this particular problem.
Risposte (1)
Matt Fig
il 21 Mar 2011
Although there appears to be nothing wrong with your multiple IF statements (except that perhaps the comparison to 1 is not necessary), why not use indexing?
legendtext2 = {'Heavy Holes' 'Light Holes' 'Spin Orbit' 'Electrons'};
legendtext2 = legendtext2([HH,LH,SO,CB])
3 Commenti
Robert Ward
il 21 Mar 2011
Walter Roberson
il 21 Mar 2011
Use function handles in connection with indexing.
Matt Fig
il 21 Mar 2011
Of course you completely left out that there was other code in your selection statements. It would make things easier on those who are trying to help you if you _specified_ the problem before posting....
Since I am not sure what other types of things, besides a call to PLOT and the assignment of a legend string, is going within your selections, I cannot help further. Perhaps if you detailed the problem.....
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!