howto find out if a vector contains only one 1 and other are 0? or how to check if every entry is the same?
e.g. i need to check if a vector contains zeros except only one 1 like:
(0 0 0 0 1 0 0 0 0) -> tr开发者_运维知识库ue
(0 0 0 0 0 0 0 0 1) -> true
(0 0 0 0 2 0 0 0 0) -> false
(0 0 1 0 1 0 0 0 0) -> false
You can use logical indexing, assuming your vector is v
: numel(v(v==1))
returns the number of elements equal to 1 in your vector.
In the same way, if you want to check if every value is the same you can use: numel(unique(v))
which returns the number of unique entries of v
.
A slightly different solution:
v = [0 0 0 0 1 0 0 0 0];
TF = sum(v==1)==1 %# returns TRUE
This is especially useful if you want to apply it to all rows of a matrix:
M = [
0 0 0 0 1 0 0 0 0 ;
0 0 0 0 0 0 0 0 1 ;
0 0 0 0 2 0 0 0 0 ;
0 0 1 0 1 0 0 0 0
];
TF = sum(M==1,2)==1
The result:
>> TF
TF =
1
1
0
0
The check for only zeroes could be achieved by extracting all unique elements from your variable:
u = unique (v)
You can then compare the result to zero and voila.
To check for a non-zero element, use the find
function. If it finds only one index and that entry is one, your desired result is true. Otherwise it's false.
function bool = oneone(vector)
num = find(vector);
bool = isscalar(num) && vector(num)==1;
end
For all same entries, the diff
function calculates the difference of subsequent elements. If any
of the results are non-zero, your desired result is false.
function bool = allsame(vector)
d = diff(vector);
bool = ~any(d);
end
精彩评论