How to use scipy.sparse.dia_matrix

Asked 2 years ago, Updated 2 years ago, 155 views

See the documentation for instructions on how to use scipy.sparse.dia_matrix.

dia_matrix(data, offsets), shape=(M,N))
where the data [k,:] stores the diagnostic entries for diagnostic offsets [k]

The following examples are shown along with the description that :I'm not sure how offset works on a data array of three rows and four columns to make it four rows and four columns.I would appreciate it if you could let me know

data=np.array([1,2,3,4]]).repeat(3,axis=0)
offsets = np.array ([0,-1,2])
dia_matrix ((data, offsets), shape=(4,4)).tearray()
array([1,0,3,0],
       [1, 2, 0, 4],
       [0, 2, 3, 0],
       [0, 0, 3, 4]])

python scipy

2022-09-30 19:46

1 Answers

shape=(4,4) is the reason why it becomes 4 rows and 4 columns.
shape=(m,n) for "m row n column".

import numpy as np
from scipy.sparse import dia_matrix
data = np.array ([1, 2, 3, 4], [10, 20, 30, 40], [100, 200, 300, 400])
print("data=")
print(data)
offsets = np.array ([0,-1,2])
dm=dia_matrix(data, offsets), shape=(4,4)).tearray()
print("dm=")
print(dm)

Results

data=
[[  1   2   3   4]
 [ 10  20  30  40]
 [100 200 300 400]]
dm =
[[  1   0 300   0]
 [ 10   2   0 400]
 [  0  20   3   0]
 [  0   0  30   4]]

If you tried shape=(3,5), the results would be as follows:

dm=
[[  1   0 300   0   0]
 [ 10   2   0 400   0]
 [  0  20   3   0   0]]


2022-09-30 19:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.