Sparse Matrix build efficiency
Show older comments
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
Accepted Answer
More Answers (2)
Steven Lord
on 7 Jun 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 Comment
acivil acivil
on 8 Jun 2017
Edited: acivil acivil
on 8 Jun 2017
Christine Tobler
on 7 Jun 2017
0 votes
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.
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!