arc_lupus arc_lupus -4 years ago 148
C++ Question

Replace `sparse.eye` with an armadillo function

I have a python script I would like to rewrite in C++, using armadillo. In python I have one line

matrix = 1/(12*h)*(sparse.eye(num_points, k = -2, dtype=np.complex).toarray() * 1 + sparse.eye(num_points, k = -1, dtype=np.complex).toarray() * -8 + sparse.eye(num_points, k = 1, dtype=np.complex).toarray() * 8 + sparse.eye(num_points, k = 2, dtype=np.complex).toarray() * -1)

which generates me a matrix where all values except the five main diagonals are zero. Unfortunately I could not find a similar function in armadillo, the onliest way I can see at the moment is to create a
-matrix, then set the diagonals with
, and then zero the rest. Is there an easier way to do that?

Answer Source

The following code should have equivalent functionality:

// sparse matrices have all values as zero at initialization
sp_mat X(10,10);

X.diag(-2).fill( 1);
X.diag(+1).fill( 8);

X *= 1.0 / (12*h);  // the .0 in 1.0 tells the compiler to use the double type
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download