How to deal with nonzero elements from rows of sparse matrix in Matlab?

房东的猫 提交于 2019-12-10 12:12:16

问题


I am dealing with quite a big sparse matrix, its size is about 150,000*150,000. I need to access into its rows, extract the non-zero elements and replace these values following the rule as the code below:

tic
H = [];
for i = 1: size(A,2)
    [a,b,c] = find(A(i,:)); % extract the rows
    add = diff([0 c(2:end) 0]); % the replacing rule
    aa = i*ones(1,size(a,2)); % return back the old position of rows
    G0 = [aa' b' add']; % put it back the old position with replaced values 
    H = [H; G0];    
end
H1 = H(:,1);
H2 = H(:,2);
H3 = H(:,3);
ADD = sparse(H1,H2,H3,nm,nm,nzmax);
toc

I found that the find function is really time consuming (0.1s/rows) in this code and with this current size of my sparse matrix, it takes me up to about 33 hours for this job. I do believe there is some ways out but I am such a newborn to coding and dealing with sparse matrix is really scary.

Would you drop me some ideas?


回答1:


You can use the find function once applying it on the whole array then use accumarray to apply the function on each row:

[a b c]=find(A.');
add=accumarray(b,c,[],@(x){diff([0 ;x(2:end) ;0])});
H = [b a vertcat(add{:})];


来源:https://stackoverflow.com/questions/45653799/how-to-deal-with-nonzero-elements-from-rows-of-sparse-matrix-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!