Counting the number of elements in matlab
I am new to MATLAB. Suppose I have a vector like x = [1 1 1 1 1 1 0 0 1 0]. I want to calculate the total number of elements in the vector and the number of non zero elements in the vector. Then come up with a ratio of both the numb开发者_StackOverflowers. I am searching in MATLAB help. how to do count of elements, but till now I didn't get any luck. If anyone provide me with help, it would be of great help. Thanks in advance.
You can get the number of elements with numel(x)
.
You can get the number of non-zeros with sum(x ~= 0)
.
So the ratio is one divided by the other.
The right way to find the number of nonzero elements (in general) is to use the nnz()
function; using sum()
also works in this particular case but will fail if there are numbers other than zero and one in the matrix used. Therefore to calculate the total element count, nonzero element count, and ratio, use code like this:
x = [1 1 1 1 1 1 0 0 1 0];
nonzeroes = nnz(x);
total = numel(x);
ratio = nonzeroes / total;
The ratio of non-zero elements to all elements in a vector is:
r = length(find(x)) / length(x)
What length
does is kind of obvious. find
gives you the index of all non-zero elements.
Edit: Fixed mistake of using size instead of length.
a= numel(find(x))/numel(x)
is another way to do it.
精彩评论