2

是否有一种很好的向量化方法来获取八度音阶(或matlab)中稀疏矩阵每一列中所有非零元素的乘积(返回乘积的行向量)?

4

2 回答 2

4

我会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-07T01:28:22.217 回答
0

我找到了解决这个问题的另一种方法,但在最坏的情况下它可能会更慢并且不太精确:

只需记录所有非零元素的对数,然后对列求和。然后取结果向量的 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);
endfunction
于 2013-04-09T20:57:06.100 回答