简体   繁体   English

计算矩阵每列中的非零条目

[英]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 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. 我不知道如何做到这一点,因为sizelengthnumel似乎不符合要求。 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!). 这是我可以建议的另一个解决方案,它对于密集矩阵而言速度不是很快,但对于稀疏矩阵来说速度非常快(感谢@ user1877862!)。 This also would mimic how one might do this in a compiled language, like C or Java, and perhaps for research purposes too. 这也可以模仿人们如何用C或Java等编译语言来实现这一点,也可能用于研究目的。 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. find输出矩阵满足函数参数内部某些布尔条件的行和列位置。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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