代码详解:用Python构建邻域矩阵( 七 )

创建矩阵

首先 , 我们将使用numpy索引创建这样的矩阵:

import numpy as np

a = np.array([1 2 3 4 5 6
)

i = [0 0 1 1 2 2

a[i

# array([1 1 2 2 3 3
)

但你会发现它不适用于多维度数组 。

我们选择的解决方案是使用scipy稀疏矩阵 , 其可在索引列表中创建 。 例如 , 使用稀疏矩阵创建大小为N = 4的对角矩阵 , 可以表示为:

from scipy import sparse

i_index = [0 1 2 3

j_index = [0 1 2 3

values = [1 1 1 1

matrix = sparse.coo_matrix((values (i_index j_index)) shape=(4 4))

推荐阅读