简体   繁体   English

稀疏矩阵每一行中非零元素的平均值

[英]The mean value of non-zero elements in each row of a sparse matrix

In the following sparse matrix:在以下稀疏矩阵中:

A=[1 1 1 3];
C = sparse(A',1:length(A),ones(length(A),1),4,4);
C =

   (1,1)        1
   (1,2)        1
   (1,3)        1
   (3,4)        1

>>full(C)

ans =

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

How could I compute the mean value of non-zero elements in each row?如何计算每行中非零元素的平均值? I couldn't use the built-in mean function of matlab on these sparse matrices.我不能在这些稀疏矩阵上使用 matlab 的内置均值 function。 I found this similar question and I can apply it to my problem我发现了这个类似的问题,我可以将其应用于我的问题

[row, ~, v] = find(C);
K>> rowmean = accumarray(row, v, [], @mean);
K>> rowmean 

rowmean =

     1
     0
     1

However, I would like to get zero value for the last row instead of this row being removed from the answer.但是,我想为最后一行获得零值,而不是从答案中删除这一行。

Approach 1方法一

You can specify the output size as the third input ofaccumarray :您可以指定 output 大小作为accumarray的第三个输入:

[row, ~, v] = find(C);
rowmean = accumarray(row, v, [size(C,1), 1], @mean);

If desired, you can use the sixth input of accumarray to obtain sparse output:如果需要,您可以使用accumarray的第六个输入来获得sparse output:

rowmean = accumarray(row, v, [size(C,1), 1], @mean, 0, true);

Approach 2方法二

You can do something simpler like this.你可以做一些像这样更简单的事情。 The result is sparse :结果是sparse的:

rowmean = sum(C, 2) ./ sum(C~=0, 2); % mean of nonzeros in each row, manually
rowmean(isnan(rowmean)) = 0; % replace NaN (resulting from 0/0) by 0

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

相关问题 一种计算每列或一行非零元素平均值的有效方法 - An efficient way to calculate the mean of each column or row of non-zero elements 计算矩阵每行中的非零元素 - Count non-zero elements in every row of matrix 从矩阵的每一行中获取前 2 个非零元素 - Get the first 2 non-zero elements from every row of matrix 计算2D NumPy数组中每行和每列内的非零元素 - Counting non-zero elements within each row and within each column of a 2D NumPy array 找到给定矩阵的每一行中最后一个非零元素的索引? - Find the index of the last non-zero element in each row of a given matrix? Python:在将每行与矩阵中的每隔一行进行比较后,存储非零唯一行的索引 - Python: Store indices of non-zero unique rows after comparing each rows with every other row in a matrix 在每个轴上查找非零元素的最大索引 - Finding largest indices of non-zero elements along each axis 如何将每个 numpy 列中的所有非零元素分配给大小与列数相同的数组中的值? - How to assign all non-zero elements in each numpy column to a value in an array whose size is the same as the number of columns? NumPy - 在 nd 数组的每一列中查找和打印非零元素 - NumPy - Finding and printing non-zero elements in each column of a n-d array 沿着下三角形numpy数组的每一行翻转非零值 - Flip non-zero values along each row of a lower triangular numpy array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM