如何处理Matlab中稀疏矩阵行中的非零元素? [英] How to deal with nonzero elements from rows of sparse matrix in Matlab?
问题描述
我正在处理相当大的稀疏矩阵,其大小约为150,000 * 150,000.我需要访问其行,提取非零元素,并按照以下代码的规则替换这些值:
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
我发现该代码中的find
函数确实非常耗时(0.1s/行),并且由于当前的稀疏矩阵大小,这项工作最多需要花费33个小时.我确实相信有一些出路,但是我对编码和处理稀疏矩阵真的很天生.
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.
您能给我一些想法吗?
推荐答案
一旦将find
函数应用于整个数组,便可以使用find
函数,然后使用accumarray
将该函数应用于每一行:
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{:})];
这篇关于如何处理Matlab中稀疏矩阵行中的非零元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!