Using Logical Operators && and ||

80 vues (au cours des 30 derniers jours)
ImpactMike
ImpactMike le 26 Mar 2019
Modifié(e) : Guillaume le 26 Mar 2019
Hi all,
I have a large data set that I'm trying to sort through (data is all numerical). To make things simple, I'd like to target values of variables within a certain number class.
I have 3 variables: Var1, Var2 and Var3. My goal is:
  • If all three (3) variables are above 20, I would like to assign 'all_max' to another variable result.
  • If any two variables - that is Var1 and Var2 or Var1 and Var 3 or Var2 and Var3, are between 20, I would like to assign 'part_max' to the variable result.
Here is a part of my MATLAB code:
if ((Var1 && Var2 && Var3) > 20) % I've tried with and without the bracket in bold - doesn't give the output I'm seeking
result = 'all_max'
elseif (Var1 && Var2 > 20) || (Var1 && Var3 > 20) || (Var2 && Var3 > 20)
result = 'part_max'
else result = 'min'
end
I've run the above code but I'm not getting the results that I need. There's probably something wrong with my logical operators.
NB: There is more to this code including a for-loop which works perfectly. Just the problem above

Réponses (2)

Guillaume
Guillaume le 26 Mar 2019
Modifié(e) : Guillaume le 26 Mar 2019
I may sound like a broken record but I keep on saying on this forum: Don't number variables. If your variables are numbered, it's a clear indication that you should have just one variable that you index.
If you do that it makes your problem trivial to solve as well:
%instead of Var1, Var2, Var3, have a single variable Var (preferably with a more meaningful name)
%Whenever you used Var1, you now use Var(1), etc.
if all(Var > 20)
result = 'all_max';
elseif nnz(Var > 20) == 2 %you could use sum instead of nnz
result = 'part_max';
else %don't forget to end an elseif... with an else
result = 'something_else'
end
See how much simpler the conditions are to write.
The advantage of the above is that it doesn't matter if you have 3 variables or 50,000. You can you the same code. Try writing the test for 50,000 numbered variables!

Alex Mcaulley
Alex Mcaulley le 26 Mar 2019
Try this:
if Var1>20 && Var2>20 && Var3>20 % I've tried with and without the bracket in bold - doesn't give the output I'm seeking
result = 'all_max'
elseif (Var1>20 && Var2>20) || (Var1>20 && Var3>20) || (Var2>20 && Var3>20)
result = 'part_max'
else result = 'min'
end

Catégories

En savoir plus sur Variables 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