获取稀疏矩阵的每列中所有非零元素的乘积

时间:2013-04-07 01:19:01

标签: matlab octave vectorization sparse-matrix multiplication

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

2 个答案:

答案 0 :(得分:4)

我将findaccumarray合并:

%# 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

答案 1 :(得分: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