Search code examples
matlaboctavevectorizationsparse-matrixmultiplication

Take the product of all nonzero elements in each column of a sparse matrix


Is there a well-vectorized way to take the product of all the nonzero elements in each column of a sparse matrix in octave (or matlab) (returning a row-vector of products)?


Solution

  • I'd combine find with 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)
    

    Some alternatives (that might be less efficient; you may want to profile them)

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