Sparse Matrix build efficiency
Mostrar comentarios más antiguos
Hello everyone.
I want to build a nxn matrix A as sparse for efficiency( time of the inversion(A\)). i)I would like to ask is it ok if I define it with the command A=sparse([..],[..],[..],n,n) with one or a few non zero elements at the beginning and then add the rest of the elements with commands like the following: A(..:..,..:..)=..; or will it cause a problem with time efficiency like when we change the size of a regular matrix or vector inside a loop and we get the warning "consider preallocating for speed"?
I can't directly compare it in terms of time efficiency with the case of building the three necessary vectors [..] from the beginning and use only the command sparse, because I have to change many things in my code to do that.
ii) Is it nessesary or possible in MATLAB to store a matrix in skyline format along with the corresponding vector of the positions of the diagonal elements?
Thank you in advance
Respuesta aceptada
Más respuestas (2)
Steven Lord
el 7 de Jun. de 2017
Inverting a matrix is generally not a good idea, and it's especially not recommended with a sparse matrix.
>> rng default
>> A = sprand(100, 100, 0.1);
>> invA = inv(A);
>> nnz(A)
ans =
951
>> nnz(invA)
ans =
10000
While invA is stored in the sparse storage format, it's not actually sparse; all its elements are nonzero.
If you're trying to invert the matrix to solve a system of equations A*x = b use the backslash operator x = A\b or, if your matrix is REALLY large, try one of the functions in the "Iterative Methods and Preconditioners" section of this documentation page.
Getting back to your question about efficiently creating a sparse matrix, if you must create it with a few elements to start then add in additional elements iteratively I would use the spalloc function first.
1 comentario
acivil acivil
el 8 de Jun. de 2017
Editada: acivil acivil
el 8 de Jun. de 2017
Christine Tobler
el 7 de Jun. de 2017
0 votos
i) You should expect constructing a sparse matrix in a loop by adding elements using indexing A(i, j) = s to be slower than constructing the three vectors i, j, s for the whole matrix, and then calling sparse once. But before making a large change to your code, you may want to profile your code, to check whether the construction of the matrix is the bottleneck.
ii) It's not possible or necessary in MATLAB to represent a matrix in the skyline format. If you are using backslash (x = A \ b), this will detect if a sparse matrix A has a banded structure.
Also, as Steve mentioned, you should definitely not invert a sparse matrix - the result will be nearly dense. To solve a linear system, use backslash instead.
Categorías
Más información sobre Resizing and Reshaping Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!