Mathematically, a vector is a tuple of n real numbers where n is an element of the Real (R) number space. Each number n (also called a scalar) represents a dimension. For example, the vector v = (x, y, z) denotes a point in the 3-dimensional space where x, y, and z are all Real numbers.
Q So how do we create a vector in Python?
A We use the ndarray class in the numpy package.
Following code snippet explains this:
from numpy import array # Define a row vector v = array([10, 20, 30]) # Being a row vector, its shape should be a 1 x 3 matrix print("Shape of the vector:",v.shape)
However, the shape of the row vector is displayed as a 1-dimensional array and not as a 1 x n
matrix.
Shape of the vector v: (3,)
This way of creating a row vector is not wrong. Because although this is a 1-dimensional array, numpy will broadcast it as a 1 x n
matrix while performing matrix operations. Following code will explain this better:
from numpy import array # Define a vector v = array([10, 20, 30]) # Define a matrix M = array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) print("Shape of M:",M.shape) # calculate v*M P = v.dot(M) print(P)
Shape of M: (3, 3) [300 360 420]
Now lets try to find the transpose of a row vector
from numpy import array # Define a row vector v = array([10, 20, 30]) print("Shape of the vector v:",v.shape) # Find the transpose of the row vector v # Mathematically, it should now become a column vector i.e., n x 1 matrix print("Transpose of vector v:",v.T)
Shape of the vector v: (3,) Transpose of vector v: [10 20 30]
Transpose does not change anything. It is still the same 1-dimensional array. To overcome this problem (although it is not a problem per se because numpy will broadcast this vector in case of vector-matrix related operations), the 1-dimensional vector can be changed to a 2-dimensional vector using any of the following two methods:
1. Use two bracket pairs instead of one to create a 2-dimensional array
from numpy import array # Define a row vector v = array([[10, 20, 30]]) # Being a row vector, its shape should be a 1 x 3 matrix print("Shape of the vector v:",v.shape) # Find the transpose of the row vector v # Mathematically, it should now become a column vector print("Transpose of vector v:\n",v.T)
Shape of the vector v: (1, 3) Transpose of vector v: [[10] [20] [30]]
2. Use newaxis
to increment the dimension of the 1-dimensional array
from numpy import array from numpy import newaxis # Define a row vector v = array([10, 20, 30])[newaxis] # Being a row vector, its shape should be a 1 x 3 matrix print("Shape of the vector v:",v.shape) # Find the transpose of the row vector v # Mathematically, it should now become a column vector print("Transpose of vector v:\n",v.T)
Shape of the vector v: (1, 3) Transpose of vector v: [[10] [20] [30]]