Python Matrix

By | September 28, 2019

In this tutorial, we will discuss matrix in python, and we also scratch some basic of Python NumPy module.

What is a Matrix:

In general, a matrix is a mathematical concept to represent equations in a 2-D structure, using rows and columns.

Python Matrix:

In python, we do not have an inbuilt matrix, but we can make it using arrays or list. If we want to define matrix in python, we can say that a Matrix is a list of lists or it is an Array of arrays.

Example:

# list approach to make a Matrix

matrix = [[1,2,3,4,5],
          [6,7,8,9,10],
          [11,12,13,14,15]
         ]

In the above example, we define a list of lists, we can also call it a matrix of 3X3, here 3X3 represent the number of rows and columns present in the matrix.

Some more examples on Matrix:

matrix = [ [1,2,3,4],
           [100,200,300,400],
           [1000,2000,3000,4000]
         ]          
print("The First Row of the matrix", matrix[0])
print("The Second Row of the matrix", matrix[1])
print("The Third Row of the matrix", matrix[2])

NumPy Arrays:

NumPy is a third-party library for python, which is commonly used for data science. NumPy contains many mathematical methods and it also supports arrays. The numPy arrays are more efficient than standard python array module because we can perform matrix operation such as matrix addition, matrix multiplication, matrix subtraction, etc using NumPy arrays.

Example:

from numpy import array
arr = array([2,4,8,12,26])
print(arr)
print(type(arr)

Output:

[ 2  4  8 12 26]
<class 'numpy.ndarray'>

As standard python does not come with in-built NumPy library so you have to download it using pip command.

Terminal command to install NumPy:

pip install numpy

How to create a numpy array and matrix?

In numpy, we have various methods to create arrays and matrix (array of arrays).

  1. Use Simple numpy array() method to create array and matrix.

Example:

from numpy import array
arr = array([2,4,8,12,26])
matrix = array([[1,2,3], [4,5,6], [7,8,9]])
print("The array is: \n", arr)
print("The matrix is: \n",matrix)

Output:

The array is:
 [ 2  4  8 12 26]
The matrix is:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
  1. Use the NumPy zeros() method to create an array or matrix:

Example:

from numpy import zeros
arr_of_zeros = zeros((1,5))          # here 1 is number of rows and 5 is number of columns
matrix_of_zeros = zeros((3,3))   # it would create a 3X3 matrix
print("Array is")
print(arr_of_zeros)
print("Matrix is: ")
print(matrix_of_zeros)

Output:

Array is
[[0. 0. 0. 0. 0.]]
Matrix is:
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
  1. Use NumPy ones() method to create an array or matrix, where each element would be 1.

Example:

from numpy import ones
arr_of_ones = ones((1,5))                            # here 1 is number of rows and 5 is number of columns
matrix_of_ones = ones((3,3))     # it would create a 3X3 matrix
print("Array is")
print(arr_of_ones)
print("Matrix is: ")
print(matrix_of_ones)

Output:

Array is
[[1. 1. 1. 1. 1.]]
Matrix is:
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
  1. Use NumPy arange() and reshape() methods to create an array and a matrix respectively.

arange() method accept an integer value and create an array containing numbers from 0 to the passed integer value.

reshape() method convert the array into a matrix. It accepts two arguments representing the number of rows and columns.

Example:

from numpy import arange, reshape
arr = arange(10)
matrix = arr.reshape( (5,2))
print(arr)
print(matrix)

Output:

[0 1 2 3 4 5 6 7 8 9]
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

Matrix Operations:

Like the mathematic matrix, we can apply the arithmetic operations on the matrices had been made by using NumPy arrays. We can perform matrix operations like matrix addition, matrix transpose, matrix subtraction and matrix multiplication.

Examples:

Matrix Addition:

We can only add two matrices if they have the same number of rows and columns. To add two matrices we can use the Arithmetic “ +” operator.

Example:

import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
B = np.array([[7,8,9],[4,5,6],[1,2,3]])
print("Matrix Addtion")
print(A+B)

Output:

Matrix Addtion
[[ 8 10 12]
 [ 8 10 12]
 [ 8 10 12]]

Matrix Subtraction:

We can only subtract two matrices if they have the same number of rows and columns. To subtract two matrices we can use the Arithmetic “ -” operator

Example:

import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
B = np.array([[7,8,9],[4,5,6],[1,2,3]])
print("Matrix Subtraction")
print(A-B)

Output:

Matrix Subtraction

[[-6 -6 -6]
 [ 0  0  0]
 [ 6  6  6]]

Matrix Multiplication:

Matrix multiplication is not similar to matrix addition or Subtraction, so to perform the matrix multiplication using numpy we have to use the dot() method.

Example:

import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
B = np.array([[7,8,9],[4,5,6],[1,2,3]])
print("Matrix Multipication")
print(A.dot(B))

Output:

Matrix Multipication

[[ 18  24  30]
 [ 54  69  84]
 [ 90 114 138]]

 

Transpose a matrix:

To transpose a matrix we can use the numpy transpose method. The transpose() method will change the rows with columns.

Example:

import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print("A Transpose")
print(A.transpose())

Output:

A Transpose
[[1 4 7]
 [2 5 8]
 [3 6 9]]

Accessing elements of a matrix:

As we know that matrix is a list of lists, so like a list using the index values we can access the matrix elements.

Example:

import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print("The First element of the array", A[0][0])
print("The Element at first row and third column", A[0][2])
print("The last element of the array", A[-1][-1])

Output:

The First element of the array 1
The Element at first row and third column 3
The last element of the array 9
Access the Complete row:

We use a single sq. brackets to access a row.

Example:

import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print("The First Row is:", A[0])
print("The Second row is:", A[1])
print("The Third row is:", A[2])

Output:

The First Row is: [1 2 3]
The Second row is: [4 5 6]
The Third row is: [7 8 9]
Access the Columns:

To access a specific row we use a special syntax arr[ : , column_number].

Example:

import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print("The First Column is:", A[:, 0])
print("The Second Column is:", A[: , 1 ])
print("The Third Column is:", A[: ,2])

Output:

The First Column is: [1 4 7]
The Second Column is: [2 5 8]
The Third Column is: [3 6 9]

Slicing of a Numpy Arrays:

Like we do slicing in the list, in numpy array we use the same syntax to slice the elements. With slicing, we can access a range of array’s elements.

Example:

import numpy as np
arr = np.array([1,2,3,4,5,6,7])
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print("First 3 numbers of the array arr", arr[:3])
print("The last 3 numbers of the array arr", arr[len(arr)-3:])

Output:

First 3 numbers of the array arr [1 2 3]
The last 3 numbers of the array arr [5 6 7]
Matrix Slicing:

TO slice a matrix we use a special syntax matrix[row, columns].

Example:

import numpy as np
arr = np.array([1,2,3,4,5,6,7])
matrix = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print(matrix[:2, :4])  # two rows, four columns
print("***************")
print(matrix[:1,])  # first row, all columns
print("***************")
print(matrix[:,2])  # all rows, second column
print("***************")
print(matrix[:, 2:5])  # all rows, third to fifth column

Output:

 [[1 2 3]
 [4 5 6]]
***************
[[1 2 3]]
***************
[3 6 9]
***************
[[3]
 [6]
 [9]]

Python Tutorials


Introduction

Flow Control

Functions

Datatypes

File Handling

Object & Class

Additional Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *