简体   繁体   中英

Constructing sparse tridiagonal matrix in Eigen

How do I construct a sparse tridiagonal matrix in Eigen? The matrix that I want to construct looks like this in Python:

alpha = 0.5j/dx**2
off_diag = alpha*np.ones(N-1)
A_fixed = sp.sparse.diags([-off_diag,(1/dt+2*alpha)*np.ones(N),-off_diag],[-1,0,1],format='csc')

How do I do it in C++ using the Eigen package? It looks like I need to use the 'triplet' as documented here , but are there easier ways to do this, considering that this should be a fairly common operation?

Another side question is whether I should use row-major or column major. I want to solve the matrix equation Ax=b , where A is a tridiagonal matrix. When we do matrix-vector multiplication by hand, we usually multiply each row of the matrix by the column vector, so storing the matrix in row-major seems to make more sense. But what about a computer? Which one is preferred if I want to solve Ax=b ?

Thanks

The triplets are the designated method of setting up a sparse matrix.

You could go the even more straightforward way and use A.coeffRef(row, col) = val or A.inser(row,col) = val , ie fill the matrix element-by-element. Since you have a tridiagonal system you know the number of non-zeros of the matrix beforehand and can reserve the space using A.reserve(Nnz) . A dumb way, which nevertheless works, is:

uint N(1000);
CSRMat U(N,N);
U.reserve(N-1);

for(uint j(0); j<N-1; ++j)
    U.insert(j,j+1) = -1;
CSRMat D(N,N);
D.setIdentity();
D *= 2;
CSRMat A = U + CSRMat(U.transpose()) + D;

As to the solvers and preferred storage order that is, as I recall, of minor importance. Whilst C(++) stores contiguous data in row-major format it is up to the algorithm whether the data is accessed in an optimal way (row-by-row for row-major storage order). The correctness of an algorithm does not, as a rule, depend on the storage order of the data. Its performance depends on compatibility of storage order and actual data access patterns. If you intend to use Eigen's own solvers stick with its default choice (col-major). If you intend to interface with other libraries (eg ARPACK) choose the storage order the library prefers/requires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM