[英]Count non-zero elements in every row of matrix
I am using MATLAB. 我正在使用MATLAB。 I have a 8x1000
matrix, and I want a program that will give me a 8x1
matrix, where each entry counts the number of non-zero entries in the corresponding row of the 8x1000
matrix. 我有一个8x1000
矩阵,我想要一个程序,它将给我一个8x1
矩阵,其中每个条目计算8x1000
矩阵的相应行中的非零条目的数量。
你可以使用matrix-multiplication
-
out = (A~=0)*ones(size(A,2),1) %// A is the input matrix
A more esoteric version could use accumarray
and bsxfun
with nnz
as the function to apply the values to for each column / group of the input matrix A
. 更深奥的版本可以使用accumarray
和bsxfun
以及nnz
作为将值应用于输入矩阵A
每个列/组的函数。 Not as efficient as using sum
and matrix multiplication, but still a method to think about :): 不如使用sum
和矩阵乘法一样有效,但仍然是一种思考方法:):
B = bsxfun(@times, 1:size(A,1), ones(size(A,2),1)).';
out = accumarray(B(:), A(:), [], @nnz);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.