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?
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{:})];