[英]An efficient way to calculate the mean of each column or row of non-zero elements
[英]The mean value of non-zero elements in each row of a 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
如何計算每行中非零元素的平均值? 我不能在這些稀疏矩陣上使用 matlab 的內置均值 function。 我發現了這個類似的問題,我可以將其應用於我的問題
[row, ~, v] = find(C);
K>> rowmean = accumarray(row, v, [], @mean);
K>> rowmean
rowmean =
1
0
1
但是,我想為最后一行獲得零值,而不是從答案中刪除這一行。
您可以指定 output 大小作為accumarray
的第三個輸入:
[row, ~, v] = find(C);
rowmean = accumarray(row, v, [size(C,1), 1], @mean);
如果需要,您可以使用accumarray
的第六個輸入來獲得sparse
output:
rowmean = accumarray(row, v, [size(C,1), 1], @mean, 0, true);
你可以做一些像這樣更簡單的事情。 結果是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.