在octave (或matlab) (返回乘积的行向量)中,有没有一种很好的矢量化方法来取稀疏矩阵每列中所有非零元素的乘积?
发布于 2013-04-07 09:28:22
我把find和accumarray结合起来
%# create a random sparse array
s = sprand(4,4,0.6);
%# find the nonzero values
[rowIdx,colIdx,values] = find(s);
%# calculate product
product = accumarray(colIdx,values,[],@prod)一些替代方案(这可能效率较低;您可能想要分析它们)
%# simply set the zero-elements to 1, then apply prod
%# may lead to memory issues
s(s==0) = 1;
product = prod(s,1);。
%# do "manual" accumarray
[rowIdx,colIdx,values] = find(s);
product = zeros(1,size(s,2));
uCols = unique(colIdx);
for col = uCols(:)'
product(col) = prod(values(colIdx==col));
end发布于 2013-04-10 04:57:06
我找到了另一种方法来解决这个问题,但它可能会更慢,在最坏的情况下也不是很精确:
只需取所有非零元素的对数,然后对列求和即可。然后取结果向量的exp:
function [r] = prodnz(m)
nzinds = find(m != 0);
vals = full(m(nzinds));
vals = log(vals);
m(nzinds) = vals;
s = full(sum(m));
r = exp(s);
endfunctionhttps://stackoverflow.com/questions/15857858
复制相似问题