Checking if a matrix has all its elements filled with one or not?
4 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Andrei Bobrov
on 29 Apr 2011
variant
all(x)
3 Comments
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))
More Answers (0)
See Also
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!