Videos
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:
Copyx = [1 1 1 1 1 1 0 0 1 0];
nonzeroes = nnz(x);
total = numel(x);
ratio = nonzeroes / total;
You can just use nnz to get the number of non-zero elements in a logical array, so the number of elements in arr with the value 0 is
count = nnz( arr == 0 );
Please read Why is 24.0000 not equal to 24.0000 in MATLAB? for information about comparisons of floating point numbers, you may need to do
tol = 1e-6; % some tolerance on your comparison
count = nnz( abs(arr) < tol ); % abs(arr - x) for values equal to x within +/-tol
correct me if I'm wrong but it sounds like you want the number of occurrences of the numbers in your vector, here's an alternative if that is the case:
arr=[1 2 2;3 3 3;5 0 0;0 0 0]; % example array where 1,2,3 occur 1x,2x,3x and 5=>1x, 0=>5x
[x(:,2),x(:,1)]=hist(arr(:),unique(arr(:)));
outputs sorted category as first column, occurrences as 2nd column:
x =
0 5
1 1
2 2
3 3
5 1
Use numel
function to get number of array elements.
n_of_elements = numel( A ) ;
As you seem to be interested in checking it manually, perhaps to review matlab code, here is the trick:
1:8has8-1+1 = 8elements-5:5has5--5+1 = 11elements-10:5has5--10+1 = 16elements
So the result is:
The matrix has 8*11*16 = 1408 elements in total.
Have a look at Determine and count unique values of an array.
Or, to count the number of occurrences of 5, simply do
sum(your_matrix == 5)
Here's a list of all the ways I could think of to counting unique elements:
M = randi([1 7], [1500 1]);
Option 1: tabulate
t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);
Option 2: hist/histc
counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );
Option 3: accumarray
counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);
Option 4: sort/diff
[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);
Option 5: arrayfun
counts5 = arrayfun( @(x)sum(M==x), unique(M) );
Option 6: bsxfun
counts6 = sum( bsxfun(@eq, M, unique(M)') )';
Option 7: sparse
counts7 = full(sparse(M,1,1));