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

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

variant
all(x)

3 Comments

suppose I need to find the number of non zero elements in the vector then is there any direct command? thanks for your quick response.
@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?
>> 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

Community Treasure Hunt

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

Start Hunting!