[英]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.但是,我想为最后一行获得零值,而不是从答案中删除这一行。
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);
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.