Parallele Matrix-Vektor-Multiplikation in NumPy
In diesem Artikel werden wir diskutieren, wie man eine Matrix-Vektor-Multiplikation in NumPy durchführt.
Matrixmultiplikation mit Vektor
Für eine Matrix-Vektor-Multiplikation gibt es bestimmte wichtige Punkte:
- Das Endprodukt einer Matrix-Vektor-Multiplikation ist ein Vektor.
- Jedes Element dieses Vektors wird durch Bilden eines Skalarprodukts zwischen jeder Reihe der Matrix und dem zu multiplizierenden Vektor erhalten.
- Die Anzahl der Spalten in der Matrix ist gleich der Anzahl der Elemente im Vektor.
# a and b are matrices prod = numpy.matmul(a,b)
Für die Matrix-Vektor-Multiplikation verwenden wir die Funktion np.matmul() von NumPy , wir definieren eine 4 x 4-Matrix und einen Vektor der Länge 4.
Python3
import numpy as np a = np.array([[1, 2, 3, 13], [4, 5, 6, 14], [7, 8, 9, 15], [10, 11, 12, 16]]) b = np.array([10, 20, 30, 40]) print("Matrix a =", a) print("Matrix b =", b) print("Product of a and b =", np.matmul(a, b))
Ausgabe:
Matrixmultiplikation mit einer anderen Matrix
Wir verwenden das Punktprodukt, um eine Matrix-Matrix-Multiplikation durchzuführen. Wir werden die gleiche Funktion auch dafür verwenden.
prod = numpy.matmul(a,b) # a and b are matrices
Für eine Matrix-Matrix-Multiplikation gibt es bestimmte wichtige Punkte:
- Die Anzahl der Spalten in der ersten Matrix sollte gleich der Anzahl der Zeilen in der zweiten Matrix sein.
- Wenn wir eine Matrix der Dimensionen mxn mit einer anderen Matrix der Dimensionen nxp multiplizieren, dann ist das resultierende Produkt eine Matrix der Dimensionen mxp
Wir werden zwei 3 x 3-Matrizen definieren:
Python3
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) b = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]]) print("Matrix a =", a) print("Matrix b =", b) print("Product of a and b =", np.matmul(a, b))
Ausgabe: