if conditional 2 out of 3

조회 수: 6(최근 30일)
Zeynab Mousavikhamene
Zeynab Mousavikhamene 2020년 5월 11일
댓글: Walter Roberson 2020년 5월 12일
I have three groups of number which can be 0 or 1. like A, B and C. I want to write a conditional to be true if 2 of three values were 1. How can I do that?
The simplest way would be like:
if (A==1 && B==1) or (A==1 && C==1) or (B==1 && c==1)
but I am searching for sth shorter.
Any idea?

채택된 답변

KALYAN ACHARJYA 2020년 5월 11일
편집: KALYAN ACHARJYA 2020년 5월 11일
  댓글 수: 2
Walter Roberson
Walter Roberson 2020년 5월 12일
If the values can be something other than 0 and 1, it is not clear how you want to compare them.
(A~=0) + (B~=0) + (C~=0) >= 2 %non-zeros
nnz([A,B,C]) >= 2 %non-zeros
sum([A,B,C] == SomeValue) >= 2 %match SomeValue specifically
nnz([A,B,C] == SomeValue) >= 2 %match SomeValue specifically

댓글을 달려면 로그인하십시오.

추가 답변(0개)


Community Treasure Hunt

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

Start Hunting!

Translated by