edgarmtze
edgarmtze

Reputation: 25048

How to count occurrences of a column value in MATLAB

Let's say I have a column with 2 values 0 and 1, How would I count the occurences of the 0, and 1 and the percentage.

If the size of the matrix is 100, and I have 45 1's I will get 45%

Upvotes: 1

Views: 3640

Answers (2)

Kaushik Shankar
Kaushik Shankar

Reputation: 5619

The count_unique function allows you to find a list of unique elements and the number of times it has appeared.

Then you just need to divide the number of occurrences by the total length of vector.

Hope that helps. This function generalizes to cases in which you have more than just 2 classes of elements.

Upvotes: 3

Jonas
Jonas

Reputation: 74940

If you just have zeros and ones, you can write

percentOnes = nnz(A(:,i))/length(A(:,i)) * 100

If you want to perform the calculation on multiple columns at once, you write

percentOnes = sum(A,1)/size(A,1) * 100

EDIT

If you have -1 and +1, and you want to know how often (in percent) you get a specific value, say, 1, you can first transform your matrix

A = yourMatrix == 1;

so that A contains only 0 and 1, and then the above will work.

Upvotes: 1

Related Questions