 # Python Matrix and Introduction to NumPy A matrix is a rectangular two-dimensional structure that is made of rows and columns. Numbers and data are arranged in these rows and columns. Given below is an example of a matrix. In this example, there are 4 columns and 4 rows. The matrix is thus said to be a 4×4 matrix.   Mathematically, the matrix is an array of numbers. However, an array can have various dimensions while a matrix has only two dimensions. The numbers that are arranged in the rows and columns of the matrix are called elements of the matrix. Learn python matrix here.

## Python Matrix

Python does not have a data type available in its directory for matrices. Other methods are used to create a matrix to solve the problems that include two dimensions of variables. One of the ways of creating a matrix in Python is using the list. Two nested lists can be included as elements of the list to create a matrix. One such example is given below.

mat_1 = [[1, 2, 3], [-1, 0, -2], [2, -3, 4]]

Thus, when creating a matrix with lists, the following syntax can be followed:

List = [[row1], [row2], …, [rowN]]

The list creates a matrix that has three rows and three columns. Note that a list is a sequence data type that stores different data in a sequence, where each element is identified by a unique index. Nested lists are lists that are used inside other lists. Here is a program that can create a nested list to create a matrix in Python.

                    
mat_1 = [[1, 2, 3], [-1, 0, -2], [2, -3, 4]]

print (“mat_1” = mat_1)

print (“mat_1” = mat_1)

print (“mat_1” = mat_1)

print (“mat_1” = mat_1[-1])

column = []

for row in mat_1:

column.append (row)

print (column)



Using lists, one can create and manipulate matrices and perform functions such as adding two matrices, multiplying two matrices, and finding the transpose of a matrix. However, when there is a need of using a matrix that has multiple rows and columns, using lists can become complicated. An easier option is to use the NumPy package.

### NumPy Array

NumPy stands for Numerical Python. Its a special Python library that is used when working with arrays. It was created by Travis Oliphant in 2005. It is an open-source Python library that is available to use for free. NumPy includes various functions such as working in linear algebra, Fourier transform, and matrices. Using lists can make the process of working with arrays much slower. NumPy proves to be at least 50 times faster than Python lists. This makes NumPy an essential tool in the field of data science.

With the NumPy package, scientific computing is possible as it supports the creation of an N-dimensional array object. You will need to install NumPy to use it. You can install the anaconda distribution of Python. It includes several packages that are related to machine learning and data science along with NumPy.

NumPy package contains the numpy.matlib Matrix library. The library includes various functions and methods that can return matrices instead of ndarray objects.

The syntax of the matrix initiated using NumPy is given below:

numpy.matrix (data, dtype = None):

Here, the parameters that are passed in the function for numpy.matrix are data, that is the data that needs to be arranged in the form of an array, and dtype, that is, the data type of the returned array. When the function is used, it returns the data provided in the form of a matrix.

The array class in NumPy is called ndarray. Here is an example of creating a multidimensional array of numbers. As is usual with Python, the array created is treated as an object.

                    
import numpy as np

mat_1 = np.array([1, -2, 2])

print(mat_1)

print(type(mat_1))



### How to Create a NumPy Array?

NumPy arrays can be created in various ways. These are explained with the help of examples given below. Numeric arrays: Arrays that have elements in the form of integers, floats, and complex numbers.

                    
import numpy as np

mat_1 = np.array ([[1, 2, 3], [-1, 0, -2]])

print(mat_1)

mat_1 = np.array ([[1.2, 2, 3], [2.3, 4, 5]])

print(mat_1)

mat_1 = np.array ([[3, 4, 5], [2, 3, 4]], dtype = complex)

print(mat_1)



Identity array: Arrays that have all elements as zeroes and ones.

                    
import numpy as np

zero_array = mp.zeo ((1, 2))

print (zero_array)

one_array = np.ones (1, 5), dtype = np.int32)

print (one_array)



The dtype is specified to be 32 bits. Thus, the array can now store values from -2-31 to 2-31 -1

Using methods: arange() and shape() methods can be used to create an array using NumPy. The example is given below.

                    
import numpy as np

mat_1 = np.arange(3)

print(mat_1)

mat_2 = np.arange(9).reshape(3, 3)

print(mapt_2)



Different functions are available in the NumPy module that makes the manipulation of the working of matrices easier. These are listed below.

• #### matlib.empty()

This function returns a new matric that does not contain any data. The parameters that are passed in the function include shape, that is an integer or a tuple of integers that define the shape of the new matrix, dtype, that is, the data type of the output, and order, C or F. Thus, the syntax of the function is as follows:

numpy.matlib.empty (shape, dtype, order)

• #### numpy.matlib.zeros()

The function is used to create a matrix that contains all elements as zeroes. The parameters passed in the function include the number of rows and columns of the matrix.

• #### numpy.matlib.ones()

The function is used to create a matrix that has 1 as all its elements. It also includes its size as its parameters.

• #### numpy.matlib.eye()

The function provides a matrix that has 1 as its diagonal elements. All other elements are zeroes. The parameters that are passed in the function are the number of rows, number of columns, index of diagonal, and data type of the output. The syntax of the function is as follows.

numpy.matlib.eye(n, M, k, dtype)

• numpy.matlib.identity()

The function returns an identity matrix of the size that is passed in the parameters. An identity matrix is one with 1 at all diagonal positions.

• numpty.matlib.rand()

With the rand() method, one can get a matrix of the desired size filled with random elements.

### Matrix Operations

Now that you have learned how to create a matrix in Python using the traditional list method as well as NumPy, next we will learn how to apply various matrix operations using the NumPy library.

The most important matrix operations are explained below with examples. Using the basic concept, one can solve more complex questions based on matrix and array.

The addition operator, that is ‘+’ is used to add two matrices that are created using NumPy. The example below shows how.

                    
import numpy as np

mat_1 = np.array([[1, 2], [4, 5]])

mat_2 = np.array([[6, -3], [-5, 7]])

mat_3 = mat_1 + mat_2

print(mat_3)



### Multiplication of two Matrices

The dot() method that is available in Python library is used to multiply two matrices. Note that the ‘*’ operator cannot be used for matrix multiplication as it is designed for multiplying one-dimensional values. Here is an example of multiplication of two matrices.

                    
import numpy as np

mat_1 = np.array([[1, 2], [4, 5]])

mat_2 = np.array([[6, -3], [-5, 7]])

mat_3 = mat_1.dot(mat_2)



### Transpose of a Matrix

The numpy.transpose is used to find the transpose of the matrix. The transpose of a matrix can be found by changing the rows of the matrix into columns and columns into rows. It is also a method that is already programmed in the library of NumPy. The example is given below.

                    
import numpy as np

mat_1 = np.array([[1, 2], [4, 5]])

print(mat_1.transpose())



With NumPy, the operations that are applied on matrices become much easier because of the predefined methods. Thus, managing matrices and arrays is a straightforward process with NumPy.

### Access Matrix Elements, Rows, and Columns

As in a sequence data type such as lists or tuples, we can access the elements with the help of the index that is assigned to each element. The matrix in NumPy is also provided with a unique index with which each element can be identified. The number of indices provided to each element is equal to the number of columns of the matrix. The example is shown below.

                    
import numpy as np

mat_1 = np.array([1, 2, 4, 5])

print (mat_1)



Output:

4

                    
import numpy as np

mat_1 = np.array([[1, 2], [4, 5]])

print(mat_1)



Output:

4

### How to access rows of a matrix?

To access a single row of the matrix, the first index of the elements needs to be mentioned. The example provided below shows how through indexing, rows of a matrix can be accessed.

                    
import numpy as np

mat_1 = np.array([[1, 2], [4, 5], [-9, 0]])

print(mat_1)



Output:

[4, 5]

### How to access columns of a matrix?

To access the columns of a matrix, slicing of the elements need to be done. The example below shows how slicing can help to access the columns.

                    
import numpy as np

mat_1 = np.array([[1, 2], [4, 5], [5, -8]])

print(mat_1[:1])



Output:

[2, 5, -8]

### Slicing of a Matrix

With the help of the slicing process, one can access the elements of the matrix based on the beginning and end index of the matrix. The syntax for the index for slicing is as follows: [start: end].

If the starting index is not mentioned, that means that the slicing will begin from the beginning. That is, the start index is considered 0. The same case is followed when the end index is not passed. The slicing takes place till the end of the length of the array.

As in Python, the index can be negative as well, thus, if negative values are provided at the start index, then the slicing will begin from the end of the length of the matrix.

To perform the slicing of the matrix, one will have to follow the following syntax.

Matrix[row_start: row_end, column_start: column_end]

The first part of the start and end index refers to the row while the second refers to the column. Indexing, as is the norm with all other data structures, starts from zero. Thus, with the help of slicing a matrix, you can get the elements of the matrix as a return based on the start and end index passed in the parameter. Here is an example that shows how slicing is done.

                    
import numpy as np

mat_1 = np.array([[1, 2, 3, 4, 5]])

print(mat_1[1:3])

print(mat_1[:4])

print(mat_1[2:])

print(mat_1[:-1])



Output:

[2, 3, 4]

[1, 2, 3, 4, 5]

[3, 4, 5]

[1, 2, 3, 4, 5]

## Q & A

Q. How do you write a matrix in Python?

Answer: The matrix in Python can be written in various ways. One of the most traditional ways to create a matrix is with the help of lists. Matrices are two-dimensional data structures with rows and columns. With the help of nested lists, the matrix can be created.

Another way to create matrices will be with the help of the NumPy library that includes various functions and methods to create and manipulate matrices.

Q. How do you write a 3×3 matrix in Python?

Answer: To write a 3×3 matrix in Python, one can create a nested list that has three nested lists, each with three elements. Another method is through the ndarray object. One will have to pass the 3, 3 as the number of rows and columns respectively in the parameters of the method.

Q.How do you create a matrix list in Python?

Answer: To create a matrix, a nested list is used in Python. Here is the syntax used to create a matrix list:

List = [[row1], [row2], [row3], …, [rowN]]

Share with friends  Customize your course in 30 seconds

Which class are you in?

5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.  Ashhar Firdausi
IIT Roorkee
Biology  Dr. Nazma Shaik
VTU
Chemistry  Gaurav Tiwari
APJAKTU
Physics
Get Started
Customize your course in 30 seconds

Which class are you in?

No thanks.