MATLAB Answers

Find out if X out of Y elements of an array are true

5 views (last 30 days)
A VP on 31 May 2019
Commented: A VP on 3 Jun 2019
I have an array of 5 elements. The array is updated at any index (1,2,3,4,5) in each simulation time to a value TRUE or FALSE. In the next function, I should check if 4 out of 5 elements including the last updated element of the array are TRUE. Is there a way to check this?


Sign in to comment.

Accepted Answer

Jos (10584)
Jos (10584) on 31 May 2019
Let TF be your logical array and X the index of the last updated element then
ConditionIsMet = TF(x) && sum(TF) == 4
will be true if your condition is met.

More Answers (1)

Arvind Sathyanarayanan
Arvind Sathyanarayanan on 31 May 2019
Edited: Arvind Sathyanarayanan on 31 May 2019
You can do something like this :
X=sum(Array(:) == 1);
if X>=4
disp('4 or more elements are true')
If they are 1s and 0s, you can just count the non zero elements using the nnz() function.


A VP on 1 Jun 2019
This solves part of my question to check if sum >= 4, but does not consider the head index that was last updated. The answer posted below solved the problem.
Thank you.
Jos (10584)
Jos (10584) on 1 Jun 2019
Logically, when one element changes at a time, (let's say, the k-th), the condition that 4 out of 5 are ture, is met can only happen when that element has become true. So, logically, that check is not really necessary ...
A VP on 3 Jun 2019
Ok. This is a new learning to me. Thank you.

Sign in to comment.