Reply to topic

How to create sparse diagonal matrix efficiently

maolijian
Registered Member
Posts
2
Karma
0
Hello,
I have a large vector D ,when I want to use
Code: Select all
D.asDiagonal();
, it occured memory error.
So I change a new way to create sparse diagonal matrix
Code: Select all
1: SparseMatrix<double> mat(rows,cols);         // default is column major
2: mat.reserve(VectorXi::Constant(cols,6));
3: for each i,j such that v_ij != 0
4:   mat.insert(i,j) = v_ij;                    // alternative: mat.coeffRef(i,j) += v_ij;
5: mat.makeCompressed();                        // optional

But I found it was too slow.
I want to know how to imrove it ?
Thank you!
annayu
Registered Member
Posts
1
Karma
0
Use scipy.sparse.spdiags (which does a lot, and so may be confusing, at first), scipy.sparse.dia_matrix and/or scipy.sparse.lil_diags. (depending on the format ttrockstars login you want the sparse matrix in...)

E.g. using spdiags:

Code: Select all
import numpy as np
import scipy as sp
import scipy.sparse

x = np.arange(10)

# "0" here indicates the main diagonal...
# "y" will be a dia_matrix type of sparse array, by default
y = sp.sparse.spdiags(x, 0, x.size, x.size)
User avatar ballen
Registered Member
Posts
3
Karma
0
thanks for the advice
darrellj
Registered Member
Posts
1
Karma
0
I would like to solve a PDE using an implicit finite volume discretization. Since the problem is 3D, the matrix should be septadiagonal. I have computed the 7 diagonals (for top, bottom, east, west, north south and central point) in 7 different arrays. dqfanfeedback

 
Reply to topic

Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], Google [Bot], Mamarok, neilsimp1, Sogou [Bot], uyenb