Define a Vector – Linear Algebra

Lesson 8 Chapter 3

Let's talk about how we define a vector with Numpy. Assume we would like to define a column vector with has a size of . Take a careful look to the code below and the shape of the arrays:

# Import Numpy library import numpy as np # Rank-1 array v = np.array([0,8]) print('Shape: ', v.shape) # Rank-2 array (row vector) v = np.array([[0,8]]) print('Shape: ', v.shape) # Rank-2 array (column vector) v = np.array([[0],[8]]) print('Shape: ', v.shape)

In the above code, we defined the same arrays in terms of numeric values with different ranks and shape. At line **7**, we defined a rank-1 array (has only one dimension). At **11**, we defined a rank-2 array which is a row vector (*1 row and multiple columns*). For **defining vectors**, the *preference is how we did at line 15* which results in a rank-2 array and a column vector (

*multiple rows and 1 column*). The output of the above code is as below:

Shape: (2,) Shape: (1, 2) Shape: (2, 1)

*Remember we do NOT usually need to define vectors as we did in lines 11 or 15. That approach seemed to be a little bit complicated using all those sorts of nested Python lists! Now let's do it the easy way*:

import numpy as np # Rank-1 array v = np.array([0,8]) print('Shape: ', v.shape) # Rank-1 array (row vector) row_v = v.reshape(1,-1) print('Shape: ', row_v.shape) # Rank-1 array (column vector) column_v = v.reshape(-1,1) print('Shape: ', column_v.shape)

*What I did above?***(1)** I used **"-1"** as it indicates all rows (columns). **(2)** I used the Numpy "** reshape**" method which simply changes the shape of the array to the desired shape (

*details later in this tutorial*).

**(3)**I used "1" indexing which indicates one!

Let me explain ** the line 8 of the above **code for further illustration.

**(1)**"-1" is the total columns which are the total elements of the vector , equals 2.

**(2)**Numpy "reshape" method changes the shape to (1,2) which means the new vector () has 2 columns and only one row! It is worth to emphasize is a row vector as it only has one row.

**NOTE:** *In simple words, (1) (1,-1) means put only one row and place all elements in columns and (-1,1) means put only one column and place all elements in rows.* **Check the below figure.**