How to perform a matrix vector multiplication in linear algebra?
Let’s say A is the following mxn matrix:
And v is the following column vector that can be represented using an nx1 matrix:
At this point, if we multiply the matrix A with the vector v, we will get the following mx1 vector:
As we can see, u is another column vector that can be represented using an mx1 matrix.
How to multiply a matrix and a vector using Python NumPy?
Let’s say A is a mxn matrix and v is a column vector that has n number of rows. We can multiply A with v to get a mx1 matrix. We can use the following Python code for that purpose.
import numpy m = 3 n = 4 v = numpy.random.randint(low=1, high=10, size=(n, 1)) print("Vector v: \n", v) A = numpy.random.randint(low=1, high=10, size=(m, n)) print("Matrix A: \n", A) R = numpy.dot(A, v) print("Axv: \n", R)
Here, we are first creating a mxn matrix A and a column vector v. A and v contain random numbers as elements. We are using the function numpy.random.randint() for that purpose. All the random numbers are numbers within the half-open interval [low, high). And the size argument indicates the shape of the matrix. For example, size=(m, n) indicates that the created matrix has m rows and n columns.
Now, we are using the numpy.dot() function to multiply the matrix and the vector. Please note that A is an mxn matrix and v is a column vector containing n rows. So, the product will have m rows and 1 column.
The output of the mentioned program will be:
Vector v: [[9] [7] [5] [6]] Matrix A: [[7 3 7 1] [1 2 3 6] [8 1 5 8]] Axv: [[125] [ 74] [152]]
Similarly, we can multiply a 1xm vector with an mxn matrix and get a 1xn vector as the product. I will leave it on the reader to try out the same using NumPy.






0 Comments