In Matlab/Octave, spdiags([-8037.500 50.000 -12.500], 0:2, 1, 51)
gives following output:
(1, 1) -> -8037.5
(1, 2) -> 50
(1, 3) -> -12.500
However, when I use the following in Python, it does not produce a similar result as in Matlab/Octave:
import numpy as np
import scipy as sp
data = array([[-8037.5],
[ 50. ],
[ -12.5]])
sp.sparse.spdiags(data, np.r_[0:2 + 1].T, 1, 51).toarray()
Python's spdiags() produce following output, which is missing the 50
and -12.5
terms at 1st and 2nd indices:
array([[-8037.5, 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. ]])
I took a look at this answer to a similar question, but I am not sure where I am going wrong.
Edit:
I am trying to build a matrix A
that is made of A_diag1
, A_diag2
, and A_diag3
as shown below. I have defined A_diag1
and A_diag3
as suggested in the answer.
import numpy as np
import scipy as sp
A_diag1 = np.tile(np.array([-8037.500, 50, -12.5]), (3,1))
A_diag2 = np.reshape(np.repeat([1250, -18505, 1250], 49), (3, 49))
A_diag3 = np.tile(np.array([12.5, -50, 8037.500]), (3,1))
A = np.concatenate((sp.sparse.spdiags(A_diag1, np.r_[0:2 + 1], 1, 51).toarray(), \
sp.sparse.spdiags(A_diag2, np.r_[0:2 + 1], 49, 51).toarray(), \
sp.sparse.spdiags(A_diag3, np.r_[48:50 + 1], 1, 51).toarray()), axis=0)
However, five highlighted cells in last 3 rows and columns of A
are showing up as zeros/singular as shown in the snapshot below. I expect those highlighted cells, currently showing as zeros, to be non-zero. [You can just copy and paste the above piece of code to reproduce A
matrix from which the snapshot shown below is taken.]
EDIT2:
Following code that uses sp.sparse.diags()
works as expected. Unlike sp.sparse.spdiags
, input argument for the shape of the result (array dimensions) when using sp.sparse.diags()
must be in a list.
import numpy as np
import scipy as sp
A_diag1 = np.array([[-8037.500], [50], [-12.5]])
A_diag2 = np.reshape(np.repeat([1250, -18505, 1250], 49), (3, 49))
A_diag3 = np.array([[12.5], [-50], [8037.500]])
A = np.concatenate((sp.sparse.diags(A_diag1, np.arange(0, 2 + 1), [1, 51]).toarray(), \
sp.sparse.diags(A_diag2, np.arange(0, 2 + 1), [49, 51]).toarray(), \
sp.sparse.diags(A_diag3, np.arange(48, 50 + 1), [1, 51]).toarray()), axis=0)