Python Creating a Vector and Matrix in Numpy

2020-12-09

Intro

In this quick tip, we we look at how to use NumPy to create Vectors and Matrices. These will be common use cases when doing science programming with Python.

Creating a Vector

There are two types of vectors we can create in Numpy, Row Vectors and Column vectors. To create a row vector, we pass numpy a python list. To created a column matrix, we pass numpy a list with one list.

## Add numpy and use the np alias
import numpy as np

## Create a row vector
rowVec = np.array([1, 5, 7])
print(vecRow)

## Create a row vector
colVec = np.array([[1],
          [2],
          [3]]
print(colVec)

Creating Matrices

To create a Matrix in NumPy, we simply pass a list of lists, similar to creating a column vector.

import numpy as np

matrix = np.array([
     [1, 2],
                    [1, 2],
      ])

In the example above, we have create a 2x2 matrix, two lists of length 2.

GoTea - KoalaTea