How to Create a Matrix in Python using Numpy 


               


How to Create a Matrix in Python using Numpy



Python


In this article, we show how to create a matrix in Python using the Numpy module.

A matrix is a rectangular array of numbers arranged in rows and columns.

A matrix is a linear algebra concept.

With a matrix, we can find things such as the determinant of the matrix, the transpose of the matrix, and the inverse of a matrix.

We can also do common mathematical operations such as addition, subtraction, multiplication, and division.

To create a matrix in Python using the numpy module, we use the matrix keyword.

We will create the following matrix shown below in Python code.

Matrix

The following code to create above matrix is shown below.



So let's now go over the code.

So the first thing we must do is import the numpy module. We do so with the line, import numpy as np. The reason we put, as np, is so that we don't have to reference numpy each time; we can just use np.

We then create a variable called matrix1 and set it equal to, np.matrix([[3,1],[5,2]])

We then reference matrix1 and you can see that it produces the matrix that we pictured above.

It's a 2x2 matrix, 2 rows and 2 columns.

Just to show again it is a matrix, we use the type() function to show its data type.

And this is how we can create a matrix in Python using the numpy module.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...