如何使用numpy从1d数组创建对角矩阵?

时间:2018-01-19 20:13:54

标签: python numpy matrix linear-algebra

我正在使用Python和numpy来做线性代数。

我在矩阵上执行import sys from PyQt5.QtWidgets import * if __name__ == '__main__': app = QApplication(sys.argv) w = QTreeView() model = QFileSystemModel() model.setRootPath("") w.setModel(model) w.show() sys.exit(app.exec_()) SVD以获得矩阵U,i和V.然而,i矩阵表示为具有1行的1x4矩阵。即:numpy

我怎样才能将i矩阵表示为对角矩阵,如下所示: [ 12.22151125 4.92815942 2.06380839 0.29766152]

我正在使用的代码:

[[12.22151125, 0, 0, 0],[0,4.92815942, 0, 0],[0,0,2.06380839,0 ],[0,0,0,0.29766152]]

所以我希望我成为一个完整的对角矩阵。我是怎么做到的?

2 个答案:

答案 0 :(得分:7)

使用numpy的diag功能:

public void removeAll(){
    int size = meteos.size();
    meteos.clear();
    fireTableRowsDeleted(0, size);
}

来自文档:

  

提取对角线或构造对角线阵列。

答案 1 :(得分:1)

  

如何获取numpy以将i矩阵表示为对角矩阵,例如   因此:[[12.22151125,0,0,0],[0,4.92815942,0,0],[0,0,2.06380839,0   ],[0,0,0,0.29766152]]

您应该使用numpy.diagflat(flatted_input, k=0)Create a two-dimensional array with the flattened input as a diagonal

示例

In [1]: flatted_input = [12, 4, 2, 1]

In [2]: np.diagflat(flatted_input)

Out [2]: array([[12, 0, 0, 0],
                [0, 4, 0, 0],
                [0, 0, 2, 0],
                [0, 0, 0, 1]])