In this guide, we will be exploring how to create a matrix in Python. A matrix is a two-dimensional data structure where numbers are arranged into rows and columns.
Whether you are an aspiring Data Scientist or someone who’s just starting out in Python programming, a strong understanding of this topic will definitely help you handle complex mathematical computations.
Step 1: Using Nested Lists to Create a Matrix
One simple method to construct a matrix in Python is by using nested list comprehensions. Nested lists are a list of lists, where an inner list represents a row. In Python, this method is versatile and quite simple to understand. Below is an example:
1 2 |
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(matrix) |
And you will get the following output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Step 2: Use of NumPy Library
NumPy (Numerical Python) is a Python library used for scientific computing. NumPy provides a powerful object – an n-dimensional array that is fast and flexible, making it suitable to handle large data sets.
1 2 3 4 |
import numpy as np matrix_np = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(matrix_np) |
The output of the above code will be:
[[1 2 3] [4 5 6] [7 8 9]]
Step 3: Using the matrix() Function in NumPy
NumPy’s in-built matrix() function creates a matrix from an array-like object or a string of data. This function returns a matrix with the same data organized in a 2-dimensional array format.
1 2 3 4 |
import numpy as np str_matrix = np.matrix('1 2 3; 4 5 6; 7 8 9') print(str_matrix) |
Upon running, it will generate:
[[1 2 3] [4 5 6] [7 8 9]]
Here is the full code for your reference
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Using nested list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(matrix) # Using NumPy import numpy as np matrix_np = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(matrix_np) # Using matrix() function in NumPy str_matrix = np.matrix('1 2 3; 4 5 6; 7 8 9') print(str_matrix) |
Conclusion
Creating a matrix in Python can be achieved in multiple ways. The method you choose will depend on the specific requirements of your project or application.
By using nested lists, NumPy, or the inbuilt ‘matrix()’ function, we are able to accomplish the task easily and effectively. So there you have it! With this tutorial, you now know how to create a matrix in Python.