循环的python身份矩阵

时间:2018-11-16 20:18:23

标签: python

一个程序,它将创建一个任意大小的方阵,其对角线上的值为1,而矩阵的其余值为0

matrix = []

dimension = int (input ("Enter matrix unit size:"))

for i in range (0, dimension):
     for j in range (0, dimension):
         if i == j:
             matrix.append (1)
         else:
             matrix.append (0)
        
print (matrix)

我需要像[[],[],[]]这样的矩阵吗?
matrix[[i]].append(1)-不起作用

3 个答案:

答案 0 :(得分:1)

你可以让

matrix = [[1 if i == j else 0 for i in range(dimension)] for j in range(dimension)]

但是请注意,在NumPy / SciPy中可以方便地进行任何线性代数运算。例如,在NumPy中,将使用numpy.eye

生成单位矩阵
import numpy as np
np.eye(dimension)

以及在SciPy中,使用scipy.sparse.identity

from scipy.sparse import identity
identity(dimension)

答案 1 :(得分:1)

在进入matrix循环之前,您需要在for j上插入一行,然后将元素添加到该行而不是矩阵中。

matrix = []

dimension = int(input("Enter identity matrix size:"))

for i in range(0, dimension):
     row = []
     matrix.append(row)
     for j in range(0, dimension):
         if i == j:
             row.append(1)
         else:
             row.append(0)

print(matrix)

答案 2 :(得分:0)

import numpy as np

matrix = []

dimension = int (input ("Enter matrix unit size:"))

for i in range (0, dimension):
     for j in range (0, dimension):
         if i == j:
             matrix.append (1)
         else:
             matrix.append (0)

npmatrix = np.array(matrix)
npmatrix = npmatrix.reshape(dimension,dimension)
print(npmatrix)