简体   繁体   中英

Count non-zero entries in each column of a matrix

If I have a matrix:

A = [1 2 3 4 5; 1 1 6 1 2; 0 0 9 0 1]

A =

     1     2     3     4     5
     1     1     6     1     2
     0     0     9     0     1

How can I count the number of non-zero entries for each column? For example the desired output for this matrix would be:

2, 2, 3, 2, 3

I am not sure how to do this as size , length or numel do not appear to meet the requirements. Perhaps it would be best to remove zero entries first?

It's simply

> A ~= 0
ans =

   1   1   1   1   1
   1   1   1   1   1
   0   0   1   0   1

> sum(A ~= 0, 1)
ans =

   2   2   3   2   3

Here's another solution I can suggest that isn't very speed worthy for dense matrices but quite fast for sparse matrices (thanks @user1877862!). This also would mimic how one might do this in a compiled language, like C or Java, and perhaps for research purposes too. First find the row and column locations that are non zero, then do a histogram on just the column locations to count the frequency of how often you see a non-zero in each column. In other words:

[~,col] = find(A ~= 0);
counts = histc(col, 1:size(A,2));

find outputs the row and column locations of where a matrix satisfies some Boolean condition inside the argument of the function. We ignore the first output as we aren't concerned with the row locations.

The output we get is:

counts =

     2
     2
     3
     2
     3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM