How to make a matrix in Python

Published on Aug. 22, 2023, 12:16 p.m.

To create a matrix in Python, you can use NumPy package which provides easy and efficient ways to create, manipulate, and analyze numerical data. NumPy supports multi-dimensional arrays and matrices, making it very convenient to work with matrices.

Here is an example code that creates a 3x3 matrix using NumPy:

import numpy as np

matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(matrix)

This will output:

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

Alternatively, you can also create a matrix using the numpy.matrix() method. Here’s an example of how to create the same matrix as before using numpy.matrix():

import numpy as np

matrix = np.matrix([[1,2,3],[4,5,6],[7,8,9]])
print(matrix)

This will output the same matrix as above:

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

Note that you can perform various matrix operations with NumPy such as addition, subtraction, multiplication, dot product, transpose, and more.

Tags: