logo

Python-Matrix

In diesem Tutorial lernen wir etwas über Python-Matrizen. In Python ähnelt ein Matrixobjekt verschachtelten Listen, da sie mehrdimensional sind. Wir werden sehen, wie man mithilfe von Numpy-Arrays eine Matrix erstellt. Anschließend werden wir zum besseren Verständnis verschiedene Matrixoperationsmethoden und Beispiele sehen.

Was ist eine Matrix in Python?

Eine Matrix in Python ist ein rechteckiges Numpy-Array. Dieses Array muss zweidimensional sein. Es enthält Daten, die in den Zeilen und Spalten des Arrays gespeichert sind. In einer Python-Matrix werden die horizontalen Elementreihen als „Zeilen“ bezeichnet, während die vertikalen Elementreihen als „Spalten“ bezeichnet werden. Die Zeilen und Spalten werden wie bei einer verschachtelten Liste übereinander gestapelt. Wenn eine Matrix r Anzahl Zeilen und c Anzahl Spalten enthält, wobei r und c positive ganze Zahlen sind, dann bestimmt r x c die Reihenfolge dieses Matrixobjekts.

Avl-Baum

Wir können Zeichenfolgen, Ganzzahlen und Objekte anderer Datentypen in einer Matrix speichern. Daten werden in den Stapeln von Zeilen und Spalten in einer Matrix gespeichert. Die Matrix ist eine entscheidende Datenstruktur für Berechnungen in Mathematik und Naturwissenschaften. In Python betrachten wir eine Liste von Listen oder eine verschachtelte Liste als Matrix, da Python keinen integrierten Typ für ein Matrixobjekt enthält.

Im Verlauf dieses Tutorials werden wir die folgende Liste von Matrixoperationsmethoden durchgehen.

  • Matrixaddition
  • Matrix-Multiplikation
  • Matrixmultiplikationsoperator
  • Matrixmultiplikation ohne Numpy
  • Matrix invers
  • Matrix transponieren
  • Matrix zu Array

Wie funktionieren Matrizen in Python?

Wir schreiben Daten in ein zweidimensionales Array, um eine Matrix zu erstellen. Dies geschieht wie folgt:

Beispiel

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

Es zeigt eine Matrix mit 3 Zeilen und 5 Spalten an, ihre Dimension beträgt also 3×5. Die Daten in dieser Matrix bilden Objekte vom Datentyp Ganzzahl. Zeile1, die erste Zeile, hat die Werte (2, 3, 5, 7, 6), während Zeile2 die Werte (3, 2, 6, 7, 2) und Zeile3 die Werte 5, 7, 2, 6, 1 hat. Bezüglich Spalten, Spalte1 hat Werte (2, 3, 5), Spalte2 hat Werte (3, 2, 7) und so weiter.

Beispiel

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

Es zeigt eine Matrix mit 3 Zeilen und 3 Spalten an, ihre Dimension beträgt also 3×3. Solche Matrizen mit gleichen Zeilen und Spalten werden quadratische Matrizen genannt.

In ähnlicher Weise ermöglicht Python Benutzern, ihre Daten in einer m x n-dimensionalen Matrix zu speichern. Wir können die Addition von Matrizen, Multiplikationen, Transpositionen und andere Operationen an einer Matrix-ähnlichen Struktur durchführen.

Die Implementierung eines Matrixobjekts in Python ist nicht einfach. Wir können eine Python-Matrix erstellen, indem wir Arrays verwenden und diese auf ähnliche Weise verwenden.

NumPy-Array

Die wissenschaftliche Computersoftware NumPy unterstützt ein robustes N-dimensionales Array-Objekt. Die Installation von NumPy ist eine Voraussetzung für die Verwendung in unserem Programm.

NumPy kann nach der Installation verwendet und importiert werden. Die Kenntnis der Grundlagen von Numpy Array wird zum Verständnis von Matrizen hilfreich sein.

Arrays mit mehreren Dimensionen von Elementen werden von NumPy bereitgestellt. Hier ist eine Illustration:

Code

 # 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)) 

Ausgabe:

 ['4' '6' 'Harry'] Data type of array object: 

Wie wir sehen können, gehören Numpy-Arrays zur Klasse ndarray.

Beispiel zum Erstellen einer Matrix mit Numpy Array

Stellen Sie sich das Szenario vor, in dem wir eine Aufzeichnung der Noten der Schüler erstellen. Wir werden den Namen und die Noten des Schülers in zwei Fächern aufzeichnen: Python-Programmierung und Matrix. Wir erstellen eine zweidimensionale Matrix mithilfe eines Numpy-Arrays und formen sie dann um.

Code

 # 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: 
', matrix) 

Ausgabe:

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

Beispiel zum Erstellen einer Matrix mit der Numpy-Matrix-Methode

Wir können die numpy.matrix verwenden, um eine 2D-Matrix zu erstellen.

Code

 # 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) 

Ausgabe:

 [[3 4] [5 6]] 

Auf Werte einer Matrix zugreifen

Über die Indizes einer Matrix kann auf die darin gespeicherten Elemente zugegriffen werden. Auf die in einer Matrix gespeicherten Daten kann mit demselben Ansatz zugegriffen werden, den wir für ein zweidimensionales Array verwenden.

Code

 # 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] ) 

Ausgabe:

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

Methoden zum Erstellen eines 2D-Numpy-Arrays oder einer Matrix

Es gibt mehrere Methoden, um ein zweidimensionales NumPy-Array und damit eine Matrix zu erstellen. Bereitstellung von Einträgen für die Zeilen und Spalten

Wir können Ganzzahlen, Gleitkommazahlen oder sogar komplexe Zahlen bereitstellen. Mit dem dtype-Attribut der Array-Methode können wir den gewünschten Datentyp angeben.

Code

 # 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: 
', array1) array2 = np.array([[1.5, 2.2, 3.1], [3, 4.4, 2]], dtype = 'float') print('Array of data type float: 
', array2) array3 = np.array([[5, 3, 6], [2, 5, 7]], dtype = 'complex') print('Array of data type complex numbers: 
', array3) 

Ausgabe:

 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]] 

Array mit Nullen und Einsen

Code

Tabelle in reagieren
 # 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) 

Ausgabe:

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

Hier haben wir dtype auf 64 Bit festgelegt.

Verwendung der Methoden arange() und shape()

Code

 # 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) 

Ausgabe:

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

Python-Matrixoperationen

Python-Matrix-Ergänzung

Wir werden die beiden Matrizen addieren und die verschachtelte for-Schleife durch die angegebenen Matrizen verwenden.

Code

 # 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) 

Ausgabe:

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

Python-Matrixmultiplikation

Python-Matrixmultiplikationsoperator

In Python ist @ als Multiplikationsoperator bekannt. Sehen wir uns ein Beispiel an, in dem wir diesen Operator verwenden, um zwei Matrizen zu multiplizieren.

Code

 # 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) 

Ausgabe:

 [[44 26] [68 42]] 

Python-Matrixmultiplikation ohne Verwendung von Numpy

Eine andere Möglichkeit, zwei Matrizen zu multiplizieren, ist die Verwendung verschachtelter Schleifen. Hier ist ein Beispiel zur Veranschaulichung.

Code

 # 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) 

Ausgabe:

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

Python-Matrix-Inverse

Wenn eine Gleichung gelöst werden muss, um den Wert einer unbekannten Variablen zu erhalten, die die Gleichungen erfüllt, wird die Umkehrung einer Matrix berechnet, die genau der Kehrwert der Matrix ist, wie wir es in der regulären Mathematik tun würden. Die Inverse einer Matrix ist die Matrix, die die Identitätsmatrix ergibt, wenn wir mit der Originalmatrix multiplizieren. Nur eine nicht singuläre Matrix kann eine Umkehrung haben. Eine nicht singuläre Matrix hat eine Determinante ungleich Null.

Code

 # 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)) 

Ausgabe:

wie man in Photoshop wiederherstellt
 [[-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-Matrixtransponierung

Python-Matrixtransponierung ohne Numpy

Bei der Transposition einer Matrix werden die Zeilen und Spalten vertauscht. Es hat das Symbol X'. Wir werden das Objekt in Zeile i und Spalte j der Matrix X in Zeile j und Spalte i der Matrix X' einfügen. Folglich wird X' zu einer 4x3-Matrix, wenn die ursprüngliche Matrix X eine 3x4-Matrix ist.

Code

 # 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) 

Ausgabe:

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

Python-Matrix-Transponierung mit Numpy

Wir können die Methode „matrix.transpose()“ in Numpy verwenden, um die Transponierung der Matrix zu erhalten.

Code

 # 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) 

Ausgabe:

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

Konvertieren einer Python-Matrix in ein Array

Wir können Ravel- und Flatten-Funktionen verwenden, um eine Python-Matrix in ein Python-Array zu konvertieren.

Code

 # 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) 

Ausgabe:

 [[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]