Since NumPy’s ndarray can handle multi-dimensional arrays, defining it as a 2-dimensional array allows you to express mathematical “matrices.”
I have corrected some typos in the provided code (such as nparray → np.array, and commas becoming dots) and will explain the concepts below. In matrix operations, the order of “Row, Column” and the slicing notation [row_range, col_range] are particularly important.
Executable Sample Code
The following code is a complete example of creating a 3×3 matrix and performing element access and extraction (slicing).
import numpy as np
def matrix_operations_demo():
print("=== 1. Matrix Creation ===")
# Create a 2D array by passing a list of lists
# Correction: Use commas for separation and np.array
x = np.array([
[11, 12, 13],
[21, 22, 23],
[31, 32, 33]
])
print(f"Matrix x:\n{x}")
print(f"Shape: {x.shape}") # (3, 3) -> 3 rows, 3 columns
print("\n=== 2. Accessing Elements (Indexing) ===")
# Syntax: x[row_index, col_index]
# Note that it starts from 0
# 0th row, 2nd column (13)
val1 = x[0, 2]
print(f"x[0, 2]: {val1}")
# 2nd row, 0th column (31)
val2 = x[2, 0]
print(f"x[2, 0]: {val2}")
print("\n=== 3. Slicing (Range Extraction) ===")
# Syntax: x[start_row:end_row, start_col:end_col]
# The rule is that the end index is "exclusive"
# Extract 0th to 1st row (before 2), and 0th to 1st column (before 2)
# This extracts the top-left 2x2 matrix
sub_matrix = x[0:2, 0:2]
print(f"x[0:2, 0:2] (Top-Left 2x2):\n{sub_matrix}")
print("\n=== 4. Extracting Rows ===")
# Specifying only one index retrieves the "row"
# All of the 0th row
row_0 = x[0]
print(f"x[0] (1st Row): {row_0}")
print("\n=== 5. Extracting Columns ===")
# ":" means "everything"
# Syntax: x[:, col_index] -> Means "specified column of all rows"
# 1st column (The middle vertical column: 12, 22, 32)
col_1 = x[:, 1]
print(f"x[:, 1] (2nd Column): {col_1}")
if __name__ == "__main__":
matrix_operations_demo()
Explanation: Rules of Index Operation
1. Specifying Coordinates x[row, col]
Unlike spreadsheet software like Excel, programming counts starting from 0.
x[0, 0]: Top left (first element)x[1, 2]: 2nd row, 3rd column
2. Slicing x[start:end]
If you write 0:2, indices 0 and 1 are targeted (2 is not included). Writing just : means “everything in that dimension.”
3. Technique for Extracting Columns x[:, i]
When you want to extract only a specific “column,” the key point is to specify : (all rows) in the row designation part. This is frequently used in data analysis to “extract data for a specific item only.”
