Create a Matrix with 2 Rows and 3 Columns: Python Code Example
Create a 2x3 Matrix in Python using NumPy
This tutorial shows you how to easily create a matrix with 2 rows and 3 columns using Python and the powerful NumPy library.
Here's the code:
# Import the NumPy library for matrix operations
import numpy as np
# Create a matrix with 2 rows and 3 columns
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# Print the matrix
print(matrix)
Output:
[[1 2 3]
[4 5 6]]
Explanation:
- Import NumPy: We start by importing the NumPy library using
import numpy as np. This line gives us access to all the functionalities of NumPy. - Create the matrix: We create a 2D array named 'matrix' using
np.array(). Inside the function, we pass a list of lists, where each inner list represents a row in our matrix:[[1, 2, 3], [4, 5, 6]]. - Print the matrix: The
print(matrix)statement displays the created matrix in the console.
Modify the Elements:
You can easily change the elements within the matrix by accessing their indices. For example, to change the element in the first row and second column to 10, you would use matrix[0, 1] = 10.
This example demonstrates the basic syntax for creating a 2x3 matrix in Python. NumPy provides numerous other functions for performing complex matrix operations, making it an essential tool for data science and scientific computing tasks.
原文地址: https://www.cveoy.top/t/topic/zzQ 著作权归作者所有。请勿转载和采集!