2013-04-07 98 views

回答

4

我與accumarray結合find

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

謝謝,我不知道有關accumarray。你知道是否有任何方法不涉及函數傳遞? – dspyz 2013-04-07 01:31:27

+0

@dspyz:你說「函數傳遞」是什麼意思? – Jonas 2013-04-07 01:57:54

+0

@dspyz假設當你說「避免函數傳遞」時,你指的是'accumarray'的'@ prod'參數 - 這是'accumarray'如何知道應用到數組的哪個函數。這是典型的,預期的語法。你爲什麼要避免它? – tmpearce 2013-04-07 02:28:27

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 
相關問題