简体   繁体   English

计算矩阵每行中的非零元素

[英]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矩阵的相应行中的非零条目的数量。

You can sum up the non-zero elements in every row, by simply converting the data to logicals before. 您可以通过简单地将数据转换为之前的逻辑来sum每行中的非零元素。

%// example data
A = randi(10,8,1000)-1;

%// count sum up non-zeros in every row
result = sum(logical(A),2)

result =

   904
   897
   909
   895
   885
   901
   903
   873

你可以使用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 . 更深奥的版本可以使用accumarraybsxfun以及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.

相关问题 从矩阵的每一行中获取前 2 个非零元素 - Get the first 2 non-zero elements from every row of matrix 稀疏矩阵每一行中非零元素的平均值 - The mean value of non-zero elements in each row of a sparse matrix Python:在将每行与矩阵中的每隔一行进行比较后,存储非零唯一行的索引 - Python: Store indices of non-zero unique rows after comparing each rows with every other row in a matrix 找到给定矩阵的每一行中最后一个非零元素的索引? - Find the index of the last non-zero element in each row of a given matrix? 计算2D NumPy数组中每行和每列内的非零元素 - Counting non-zero elements within each row and within each column of a 2D NumPy array 一种计算每列或一行非零元素平均值的有效方法 - An efficient way to calculate the mean of each column or row of non-zero elements 如何在不使用循环的情况下用列/行索引替换 (0,1) numpy 数组的非零元素? - How to replace non-zero elements of a (0,1) numpy array by it's column/ row indices without using a loop? 反转 numpy 中的非零子矩阵,返回原始形状的矩阵 - Invert non-zero submatrix in numpy, returning a matrix of original shape 返回数组中每个非零元素的索引 - Return index of every non-zero element in array numpy矢量化方法来计算整数数组中的非零位 - numpy vectorized way to count non-zero bits in array of integers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM