This website works better with desktop in both themes, for mobile devices please change to light theme.

Sparse Matrix#

[16]:
import numpy as np
from scipy.sparse import csr_matrix, bsr_matrix, csc_matrix, dia_matrix, coo_matrix

Compressed Sparse Row Matrix#

[27]:
row_idxs = [0, 0, 1, 2, 3, 3]
col_idxs = [0, 1, 2, 3, 2, 3]
values = [1, 2, 3, 4, 5, 6]

csr_matrix((values, (row_idxs, col_idxs)), shape=(4,4)).toarray()
[27]:
array([[1, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4],
       [0, 0, 5, 6]])
[47]:
row_idxs = [0, 0, 1, 2, 3, 3]
col_idxs = [0, 1, 2, 3, 3, 3]
values = [1, 1, 1, 1, 1, 1]

csr_matrix((values, (row_idxs, col_idxs)), shape=(4,4)).toarray()
[47]:
array([[1, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1],
       [0, 0, 0, 2]])

Block Sparse Row Matrix#

[28]:
row_idxs = [0, 0, 1, 2, 3, 3]
col_idxs = [0, 1, 2, 3, 2, 3]
values = [1, 2, 3, 4, 5, 6]

bsr_matrix((values, (row_idxs, col_idxs)), shape=(4,4)).toarray()
[28]:
array([[1, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4],
       [0, 0, 5, 6]])
[44]:
row_idxs = [0, 0, 1, 2, 3, 3]
col_idxs = [0, 1, 2, 3, 3, 3]
values = [1, 1, 1, 1, 1, 1]

bsr_matrix((values, (row_idxs, col_idxs)), shape=(4,4)).toarray()
[44]:
array([[1, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1],
       [0, 0, 0, 2]])

COOrdinate Matrix#

[43]:
row_idxs = [0, 0, 1, 2, 3, 3]
col_idxs = [0, 1, 2, 3, 3, 3]
values = [1, 1, 1, 1, 1, 1]

coo_matrix((values, (row_idxs, col_idxs)), shape=(4,4)).toarray()
[43]:
array([[1, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1],
       [0, 0, 0, 2]])

Diagonal Matrix#

[31]:
offset = 0 ## kind of diagonal location
values = [1, 2, 3, 4, 5, 6]

dia_matrix((values, offset), shape=(4,4)).toarray()
[31]:
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
[32]:
offset = 1
values = [1, 2, 3, 4, 5, 6]

dia_matrix((values, offset), shape=(4,4)).toarray()
[32]:
array([[0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4],
       [0, 0, 0, 0]])
[37]:
offset = [0, -1, 2]
values = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [3, 5, 8, 2]
])

dia_matrix((values, offset), shape=(4,4)).toarray()
[37]:
array([[1, 0, 8, 0],
       [5, 2, 0, 2],
       [0, 6, 3, 0],
       [0, 0, 7, 4]])
[ ]: