Optimize filling of sparse matrix: "This sparse indexing expression is likely to be slow."
14 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi,
I have a sparse matrix for which I'm replacing certain values in a foor-loop structure. It all goes on the lines of
A = sparse(n,n);
for i = 1:size(Im,1);
for j = 1:size(Im,2);
for k = 1:size(Im,3);
row = ind(i,j,k);
if(Labels(i,j,k) == -1)
continue
elseif(Labels(i,j,k) == 1) || (Labels(i,j,k) == 2)
A(row,row) = 1;
continue
end
[sx, sx_value, sy, sy_value, sz, sz_value] = myFunction(Labels,i,j,k);
A(row,ind(i+sx,j,k)) = A(row,ind(i+sx,j,k)) + sx_value;
A(row,ind(i,j+sy,k)) = A(row,ind(i,j+sy,k)) + sy_value;
A(row,ind(i,j,k+sz)) = A(row,ind(i,j,k+sz)) + sz_value;
end
end
end
end
Basically what I have is a 2D matrix Im and a (large) number n over which I create a sparse matrix A. I then loop over all dimensions (perhaps not optimal, I know) and for certain situations (that is certain rows of n) I call a function, and set values of A with the output of that function, on the lines of
A(i,j) = myValue;
For large values of n (e.g. 500, 1000, etc.) the code is very slow. I ran some profiling and the specific lines where I fill values in A indicates as
This sparse indexing expression is likely to be slow.
On the help I saw some suggestions of not doing this to sparse matrices but rather initiating e.g. A = zeros(...) and 'sparsifying' it in the end. The problem when n is large though, is that I cannot allocate enough memory for A = zeros(...).
Anyone got any suggestions of how to improve the code? Any help would be really great!
0 Commenti
Risposta accettata
Steven Lord
il 18 Lug 2017
In this case I would construct the i, j, and v vectors containing row and column indices and values respectively inside the loop. Call sparse once at the end to turn those vectors into the sparse matrix. See the "Accumulate Values into Sparse Matrix" example on the documentation page for the sparse function for a demonstration of this technique.
4 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Sparse Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!