Lopan
Lopan

Reputation: 503

Check two values in array

I have an array in Matlab called myVec and I have to execute an operation if the array contains at least one 1 and one 0. I do not know how I could do that, I tried with find but it did not work. This is what I need.

if %myVec contains 0 && myVec contains 1
    %Code A
else
    %Code B
end

I checked that if you try for example find(myVec==0)and it returned the positions which fulfill the statement, it could be used as a boolean if find(myVec==0) but then I tried if (find(myVec==0) && find(myVec==1)) and The following error is shown Operands to the || and && operators must be convertible to logical scalar values.

Thank you everyone.

Upvotes: 0

Views: 67

Answers (1)

Sardar Usama
Sardar Usama

Reputation: 19689

if sum(myVec==1) && sum(myVec==0)
    %Code A
else
    %Code B
end

% sum(myVec==1) counts the number of ones in myVec 
% sum(myVec==0) counts the number of zeros in myVec
% if myVec is a matrix with more than one rows and columns, use myVec(:) instead

Upvotes: 2

Related Questions