开发者

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 a开发者_开发技巧nd the percentage.

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜