Checking if a matrix has all its elements filled with one or not?

4 views (last 30 days)
Suppose I have a matrix like x = [1 1 1 1 1 1]. Now I have to write a if condition, where I have to check whether "x" contains all its elements as ones or not? How to do that. I searched in matlab's help, but couldn't find any direct "command" like to check such an existence.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 29 Apr 2011
variant
all(x)
  3 Comments
Abhishek
Abhishek on 29 Apr 2011
@andrei: all(x==1) returns a value 1 even if I have all zeroes as my elements. x = [0 0 0 0 0 0] which should not be the case, right?
Walter Roberson
Walter Roberson on 29 Apr 2011
>> x = [0 0 0 0 0 0]
x =
0 0 0 0 0 0
>> all(x==1)
ans =
0
So if you are getting a 1 result from that, something is wrong.
The number of non-zero elements is nnz(x)
The original answer of all(x) does not match your problem conditions, as it would return true for the situation in which all of the x are non-zero. Your variation of all(x==1) is correct for vectors. For general matrices, all(x(:)==1)
A variation would be isequal(x, ones(size(x),class(x))

Sign in to comment.

More Answers (0)

Categories

Find more on Genomics and Next Generation Sequencing in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!