How to perform vector and scalar multiplication?
If we multiply a vector with a scalar, then each component of the vector gets multiplied by the scalar. For example, let’s say r1 is a row vector, c1 is a column vector and λ is a scalar. At this point we can multiply λ with r1 or c1 to get another row vector or a column vector, respectively.
How to perform vector and scalar multiplication using Python NumPy?
We can use the following Python code to perform vector and scalar multiplication using NumPy.
import numpy r1 = numpy.random.randint(low=1, high=10, size=(1, 3)) c1 = numpy.random.randint(low=1, high=10, size=(3, 1)) l = 5 r2 = l * r1 c2 = l * c1 print("r1: \n", r1) print("l: ", l) print("r2 = l * r1: \n", r2) print("c1: \n", c1) print("c2 = l * c1: \n", c2)
We are first creating two vectors r1 and c1. Both r1 and c1 contain random integers. We are using the numpy.random.randint() function to generate random integers. Please note that the generated random integers will be within the range [low, high).
And the size argument indicates the shape of the generated vector. For example, size=(1, 3) indicates that the generated vector will have 3 components within a single row. In other words, the generated vector will be a row vector. And size=(3, 1) indicates that the generated vector will have 3 components within a single column. In other words, the generated vector will be a column vector.
Now, we perform vectorm and scalar multiplication. The output of the mentioned program will be:
r1: [[6 1 1]] l: 5 r2 = l * r1: [[30 5 5]] c1: [[1] [8] [3]] c2 = l * c1: [[ 5] [40] [15]]






0 Comments