在本教程中,我们将学习有关Python矩阵的知识。在Python中,矩阵对象类似于嵌套列表,因为它们是多维的。我们将看到如何使用Numpy数组创建矩阵。接下来,我们将看到各种矩阵操作方法和示例,以便更好地理解。

Python中的矩阵是什么?

在Python中,矩阵是一个矩形的Numpy数组。这个数组必须是二维的。它包含存储在数组的行和列中的数据。在Python矩阵中,水平的一系列项目被称为“行”,而垂直的一系列项目被称为“列”。行和列像嵌套列表一样堆叠在一起。如果一个矩阵包含r行和c列,其中r和c是正整数,则r x c确定了此矩阵对象的顺序。

我们可以在矩阵中存储字符串、整数和其他数据类型的对象。数据以行和列的堆栈方式存储在矩阵中。矩阵是数学和科学中计算的关键数据结构。在Python中,我们将列表的列表或嵌套列表视为矩阵,因为Python不包括矩阵对象的内置类型。

在本教程的过程中,我们将介绍以下矩阵操作方法的列表。

  • 矩阵加法
  • 矩阵乘法
  • 矩阵乘法运算符
  • 不使用Numpy的矩阵乘法
  • 矩阵逆
  • 矩阵转置
  • 矩阵转为数组

Python中的矩阵如何工作?

我们使用二维数组来创建矩阵中的数据。操作如下:

示例

[ 2 3 5 7 6  
  3 2 6 7 2  
  5 7 2 6 1 ]  

这显示了一个具有3行5列的矩阵,因此其维度为3×5。这个矩阵中的数据由整数数据类型的对象组成。第一行Row1的值为(2, 3, 5, 7, 6),而第二行Row2的值为(3, 2, 6, 7, 2),第三行Row3的值为(5, 7, 2, 6, 1)。关于列,Column1的值为(2, 3, 5),Column2的值为(3, 2, 7),依此类推。

示例

[ 0, 0, 1  
  0, 1, 0  
  1, 0, 0 ]  

这显示了一个具有3行3列的矩阵,因此其维度为3×3。具有相同行和列的矩阵称为方阵。

类似地,Python允许用户将数据存储在m x n维矩阵中。我们可以在类似矩阵的结构上执行矩阵的加法、乘法、转置和其他操作。

Python中的矩阵对象的实现并不直接。我们可以使用数组创建Python矩阵,然后使用它们。

Numpy数组

科学计算软件NumPy支持强大的N维数组对象。在使用它之前,需要安装NumPy。

NumPy可以在安装后使用和导入。了解Numpy数组的基础知识将有助于理解矩阵。

NumPy提供了具有多个维度的项目的数组。以下是一个示例:

代码

# Python program to show how to create a Numpy array  
  
# Importing numpy  
import numpy as np  
  
# Creating a numpy array  
  
array = np.array([4, 6, "Harry"])  
print(array)                 
print("Data type of array object: ", type(array)) 

输出:

['4' '6' 'Harry']
Data type of array object:  <class 'numpy.ndarray'>

正如我们所看到的,Numpy数组属于ndarray类。

使用Numpy数组创建矩阵的示例

想象一下,我们创建了一个学生分数记录。我们将记录学生的姓名和两门科目的分数,Python编程和矩阵。我们将使用numpy数组创建一个二维矩阵,然后对其进行重塑。

代码

# Python program to create a matrix using numpy array  
  
# Importing numpy  
import numpy as np  
  
# Creating the matrix  
record = np.array( [['Itika', 89, 91],  
                                   ['Aditi', 96, 82],  
                                   ['Harry', 91, 81],  
                                   ['Andrew', 87, 91],  
                                   ['Peter', 72, 79]])  
  
matrix = np.reshape(record, (5,3))  
print("The matrix is: \n", matrix)  

输出:

The matrix is: 
 [['Itika' '89' '91']
 ['Aditi' '96' '82']
 ['Harry' '91' '81']
 ['Andrew' '87' '91']
 ['Peter' '72' '79']]

使用Numpy Matrix方法创建矩阵的示例

我们可以使用numpy.matrix来创建一个二维矩阵。

代码

# Python program to show how to create a matrix using the matrix method  
  
# importing numpy  
import numpy as np  
  
# Creating a matrix  
matrix = np.matrix('3,4;5,6')  
print(matrix)  

输出:

[[3 4]
 [5 6]]

访问矩阵的值

可以使用矩阵的索引来访问其中存储的元素。存储在矩阵中的数据可以使用与二维数组相同的方法来访问。

代码

# Python program to access elements of a matrix  
  
# Importing numpy  
import numpy as np  
  
# Creating the matrix  
record = np.array( [['Itika', 89, 91],  
                   ['Aditi', 96, 82],  
                   ['Harry', 91, 81],  
                   ['Andrew', 87, 91],  
                   ['Peter', 72, 79]])  
  
matrix = np.reshape(record, (5,3))  
  
# Accessing record of Itika  
print( matrix[0] )  
  
# Accessing marks in the matrix subject of Andrew  
print( "Andrew's marks in Matrix subject: ", matrix[3][2] )  

输出:

['Itika' '89' '91']
Andrew's marks in Matrix subject:  91

创建2-D Numpy数组或矩阵的方法

有多种方法可以创建二维NumPy数组,从而创建一个矩阵。为行和列提供条目

我们可以提供整数、浮点数,甚至复数。使用数组方法的dtype属性,我们可以指定所需的数据类型。

代码

# Python program to show how to create a Numpy array  
  
# Importing numpy  
import numpy as np  
  
# Creating numpy arrays  
array1 = np.array([[4, 2, 7, 3], [2, 8, 5, 2]])  
print("Array of data type integers: \n", array1)  
  
array2 = np.array([[1.5, 2.2, 3.1], [3, 4.4, 2]], dtype = "float")  
print("Array of data type float: \n", array2)  
  
array3 = np.array([[5, 3, 6], [2, 5, 7]], dtype = "complex")  
print("Array of data type complex numbers: \n", array3) 

输出:

Array of data type integers: 
 [[4 2 7 3]
 [2 8 5 2]]
Array of data type float: 
 [[1.5 2.2 3.1]
 [3.  4.4 2. ]]
Array of data type complex numbers: 
 [[5.+0.j 3.+0.j 6.+0.j]
 [2.+0.j 5.+0.j 7.+0.j]]

具有零和一的数组

代码

# Python program to show how to create a Numpy array having zeroes and ones  
  
# Importing numpy  
import numpy as np  
  
# Creating numpy arrays  
zeores_array = np.zeros( (3, 2) )  
print(zeores_array)  
  
ones_array = np.ones( (2, 4), dtype=np.int64 )  
print(ones_array)  

输出:

[[0. 0.]
 [0. 0.]
 [0. 0.]]
[[1 1 1 1]
 [1 1 1 1]]

在这里,我们指定了64位数据类型。

使用arange()和shape()方法

代码

# Python program to show how to create Numpy array using arrange() and shape() methods  
  
# Importing numpy  
import numpy as np  
  
# Creating numpy arrays  
array1 = np.arange( 5 )  
print(array1)  
  
array2 = np.arange( 6 ).reshape( 2, 3 )  
print(array2)  

输出:

[0 1 2 3 4]
[[0 1 2]
 [3 4 5]]

Python矩阵操作

Python矩阵加法

我们将添加两个矩阵,并使用嵌套循环遍历给定的矩阵。

代码

# Python program to add two matrices without using numpy  
  
# Creating matrices in the form of nested lists  
matrix1 = [[23, 43, 12],     
           [43, 13, 55],     
           [23, 12, 13]]    
   
matrix2 = [[4, 2, -1],    
           [5, 4, -34],     
           [0, -4, 3]]    
    
matrix3  = [[0,1,0],    
            [1,0,0],    
            [0,0,1]]   
  
matrix4  = [[0,0,0],    
            [0,0,0],    
            [0,0,0]]  
  
matrices_length = len(matrix1)    
    
#Adding the three matrices using nested loops    
for row in range(len(matrix1)):    
    for column in range(len(matrix2[0])):    
        matrix4[row][column] = matrix1[row][column] + matrix2[row][column] + matrix3[row][column]   
#Printing the final matrix    
print("The sum of the matrices is = ", matrix4)  

输出:

The sum of the matrices is =  [[27, 46, 11], [49, 17, 21], [23, 8, 17]]

Python矩阵乘法

Python矩阵乘法运算符

在Python中,@被称为乘法运算符。让我们看一个示例,我们将使用此运算符来相乘两个矩阵。

代码

# Python program to show how to create a matrix using the matrix method.  
  
# importing numpy  
import numpy as np  
  
# Creating the matrices  
matrix1 = np.matrix('3,4;5,6')  
matrix2 = np.matrix('4,6;8,2')  
  
# Usng multiplication operator to multiply two matrices  
print(matrix1 @ matrix2)  

输出:

[[44 26]
 [68 42]]

Python矩阵乘法,不使用Numpy

另一种矩阵相乘的方式是使用嵌套循环。下面是一个示例。

代码

# Python program to show how to create a matrix using the matrix method  
  
# importing numpy  
import numpy as np  
  
# Creating two matrices  
matrix1 = [[4, 6, 2],  
     [7, 4, 8],  
     [6, 2, 7]]  
  
matrix2 = [[4, 6, 8, 2],  
           [6, 5, 3, 7],  
           [7, 3, 7, 6]]  
# Result will be a 3x4 matrix  
output = [[0,0,0,0],  
         [0,0,0,0],  
         [0,0,0,0]]  
  
# Iterating through the rows of matrix1  
for i in range(len(matrix1)):  
   # iterating through the columns of matrix2  
   for j in range(len(matrix2[0])):  
       # iterating through the rows of matrix2  
       for k in range(len(matrix2)):  
            output[i][j] += matrix1[i][k] * matrix2[k][j]  
  
for row in output:  
    print(row)  

输出:

[66, 60, 64, 62]
[108, 86, 124, 90]
[85, 67, 103, 68]

Python矩阵求逆

当需要解方程以获得满足方程的未知变量的值时,需要计算矩阵的逆,它只是矩阵的倒数,就像我们在常规数学中一样。矩阵的逆是乘以原始矩阵时得到单位矩阵的矩阵。只有非奇异矩阵才能有逆矩阵。非奇异矩阵的行列式不为零。

代码

# Python program to show how to calculate the inverse of a matrix  
    
# Importing the required library  
import numpy as np  
    
# Creating a matrix  
A = np.matrix("3, 4, 6; 6, 2, 7; 6, 4, 6")  
  
# Calculating the inverse of A  
print(np.linalg.inv(A))  

输出:

[[-3.33333333e-01 -7.40148683e-17  3.33333333e-01]
 [ 1.25000000e-01 -3.75000000e-01  3.12500000e-01]
 [ 2.50000000e-01  2.50000000e-01 -3.75000000e-01]]

Python矩阵转置

Python矩阵转置,不使用Numpy

矩阵的转置涉及交换行和列。它具有符号X'。我们将矩阵X中的对象放入矩阵X'的第i行和第j列中。因此,如果原始矩阵X是一个3x4矩阵,那么X'将变成一个4x3矩阵。

代码

# Python program to find the transpose of a matrix using nested loops  
  
# Creating a matrix  
matrix = [[4, 6, 7, 8],  
          [3, 7, 2, 7],  
          [7, 3, 7, 5]]  
  
result = [[0, 0, 0],  
          [0, 0, 0],  
          [0, 0, 0],  
          [0, 0, 0]]  
  
# iterating through the rows  
for i in range(len(matrix)):  
   # iterating through the columns  
   for j in range(len(matrix[0])):  
        result[j][i] = matrix[i][j]  
  
for row in result:  
    print(row)  

输出:

[4, 3, 7]
[6, 7, 3]
[7, 2, 7]
[8, 7, 5]

Python矩阵转置使用Numpy

我们可以使用Numpy中的matrix.transpose()方法来获得矩阵的转置。

代码

# Python program to find the transpose of a matrix  
  
# importing the required module  
import numpy as np  
                
# Creating a matrix using matrix method  
matrix = np.matrix('[5, 7, 6; 4, 2, 4]')  
                
#finding transpose using matrix.transpose method  
transpose = matrix.transpose()  
      
print(transpose)  

输出:

[[5 4]
 [7 2]
 [6 4]]

将Python矩阵转换为数组

我们可以使用ravel和flatten函数将Python矩阵转换为Python数组。

代码

# Python program to convert a matrix to an array  
  
# importing the required module  
import numpy as np  
  
# Creating a matrix using numpy  
matrix = np.matrix("[4, 6, 7; 5, 2, 6; 6, 3, 6]")  
  
# Using ravel() function to covert matrix to array  
array = matrix.ravel()  
print(array)  
  
# Using flatten() function to covert matrix to array  
array = np.asarray(matrix).flatten()  
print(array)  
  
# Using reshape() function to covert matrix to array  
array = (np.asarray(matrix)).reshape(-1)  
print(array)  

输出:

[[4 6 7 5 2 6 6 3 6]]
[4 6 7 5 2 6 6 3 6]
[4 6 7 5 2 6 6 3 6]

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程