如何在 Python 中制作矩阵

矩阵是具有精确二维的数组,这个概念在数学中非常重要。 矩阵中的所有元素都组织成行和列。 例如,下面给出的矩阵有 2 行 3 列,发音为“二乘三”矩阵。

由于python中没有内置的矩阵数据类型,所以我们可以通过以下方法创建矩阵:

  1. 通过使用嵌套列表
  2. 通过使用 numpy 数组函数
  3. 通过使用 numpy 矩阵函数
  4. 通过使用 numpy reshape 函数
  5. 通过接受用户的输入

1.通过使用嵌套列表

我们可以使用嵌套列表来创建矩阵。

A = [[5, 1, 8], [7, 5, 3], [4, 6, 3]]  for i in A:  print(i)

图 1:使用嵌套列表

输出:

图 2:输出

在图 1 中,我们在主列表中有三个子列表。 我们使用 for 循环单独遍历每一行,如图 2 所示。我们没有直接打印列表,因为这将在一行中打印列表。

2.通过使用numpy数组函数

我们可以使用 Python 中的 numpy.array() 函数创建一个矩阵。

import numpy as np  A = np.array([[1, 2, 3], [3, 4, 5]])  print(A)  print('No. of Dimensions:', A.ndim)  print('Dimensions:', A.shape)

文本描述自动生成

图 3:使用 numpy.array() 函数

输出:

文本描述自动生成

图 4:输出

在图 3 中,我们将 numpy 模块作为 np 导入,并将 np.array 函数作为嵌套列表传递,它创建一个矩阵,而它的维度可以在图 4 中看到,包含 2 行和 3 列。

3. 通过使用 numpy 矩阵函数

numpy 模块的 Matrix 函数从类似数组的对象或从一串数据返回一个矩阵。 在 python 中,矩阵对象继承了 ndarray 对象的所有属性和方法。

示例 1

import numpy as np  A= np.matrix([[1, 2, 6], [3, 4, 8],[4,8,9]])  print(A)  print(type(A))

文本描述自动生成

图 5:使用 numpy.matrix() 函数进行数组输入

输出:

文本描述自动生成

图 6:输出

在图 5 中,我们将 numpy 模块作为 np 导入,并向 np.matrix 函数传递一个嵌套列表。 创建一个属于 numpy.matrix 类的 3×3 矩阵。

示例 2

import numpy as np  A = np.matrix('4 7 8; 7 9 1')  print(A)

文本描述自动生成

图 7:使用 numpy.matrix() 函数进行字符串输入

输出:

图 8:输出

在示例 2 中,我们将 numpy.matrix 函数作为字符串矩阵传递,我们用逗号或空格分隔列,而用分号分隔行。 输出矩阵有 2 行 3 列,如图 8 所示。

4. 通过使用 numpy Reshape Function

numpy.reshape() 也可以用来创建矩阵,这个函数改变数组的形状,所以我们可以用它来改变一维数组的形状到二维数组而不改变元素。 在改变数组的形状之前,我们必须检查数组中元素的数量。

import numpy as np  A = np.array([[4,1,8,7,5,7,9,6,8]]).reshape(3,3)  print("Matrix= n", A)  print("Dimensions = ", A.shape)

计算机的屏幕截图 以中等可信度自动生成的描述

图 9:使用 numpy.reshape() 函数

输出:

文本描述自动生成

图 10:输出

在上面的示例中,我们有一个由九个元素组成的一维数组,而 reshape() 函数将其更改为一个二维数组,因此元素以 3×3 的维度排列,具有 3 行和 3 列。

5. 接受用户的输入

在 Python 中,我们也可以创建一个接受用户输入的矩阵。

row = int(input("enter the number of rows:"))  col = int(input("enter the number of columns:"))  # Initialize matrix  m = []  print("enter the entries row wise:")  # For user input  for i in range(row): # A for loop for row entries  a = []  for j in range(col): # A for loop for column entries  a.append(int(input()))  m.append(a)  # For printing the matrix  for i in range(row):  for j in range(col):  print(m[i][j], end=" ")  print()

文本描述自动生成