In python 2.7, I'm trying to create a sparse matrix with 3 diagonals. The matrix should look like this:
[[ 10 0 0 0 -19 0 0 0 10 0 0 0 ... 0]
[ 0 10 0 0 0 -19 0 0 0 10 0 0 ... 0]
[ 0 0 10 0 0 0 -19 0 0 0 10 0 ... 0]
[ -1 1 1 0 0 0 0 0 0 0 0 0 ... 0]]
My code is
import numpy as np
import numpy.matlib
import scipy.sparse
Dk = np.array([[ 10.], [ 10.],[ 10.]])
Ns = 3
N = 100
z = np.array([[-1.],
[ 1.],
[ 1.]])
dg0 = np.array([numpy.matlib.repmat(1-2*Dk,1,1)])
dgn = np.array([numpy.matlib.repmat(Dk,1,1)])
dgp = np.array([numpy.matlib.repmat(Dk,1,1)])
B = np.zeros((Ns+1,N))
dg0 = np.append(dg0,0)
dgn = np.append(dgn,0)
dgp = np.append(dgp,0)
zerosN1 = np.zeros((1,Ns+1))
zerosN2 = np.zeros((1,2*(Ns+1)))
dg0 = np.append(zerosN1,dg0)
dgp = np.append(zerosN2,dgp)
data0 = np.array([dgn,dg0,dgp])
diags0 = np.array([0,Ns+1,2*(Ns+1)])
B = scipy.sparse.spdiags(data0, diags0, Ns+1, N)
B = scipy.sparse.lil_matrix(B)
zerosN = np.zeros((1,N-Ns))
B[3] = np.append(z,zerosN)
I am getting an error: ValueError: number of diagonals (1) does not match the number of offsets (3)
I don't understand what's wrong. I'd appreciate any help.
Your problem is that data0
looks like this:
array([array([ 10., 10., 10., 0.]),
array([ 0., 0., 0., 0., -19., -19., -19., 0.]),
array([ 0., 0., 0., 0., 0., 0., 0., 0., 10., 10., 10.,
0.])], dtype=object)
I'm not sure what you're doing with repmat
(or a lot of parts of your program, for that matter), as all you have to do to create a sparse matrix from diagonals is provide the same number of diagonals (of the same length) as the offsets provided. Thus, this should suffice:
flattened_Dk = Dk.ravel()
data0 = [flattened_Dk, 1-2*flattened_Dk, flattened_Dk]
B = scipy.sparse.diags(data0, diags0, shape=(Ns,N))