如何高效生成随机矩阵并执行矩阵乘法?附空列表追加实现
Hey Shahid! Let's fix up your matrix multiplication code using list appends, and also cover smarter ways to generate random matrices and optimize the multiplication itself.
First: Fixing the Pure Python Implementation (List Append Style)
Your existing code has a few gaps (like an uninitialized res_matrix and missing mat2 setup). Here's a complete, working version that sticks to the list append approach you requested:
import random # Define the size of your square matrices (adjust this value as needed) order = 3 # Generate random matrix 1 using list appends mat1 = [] for _ in range(order): # Use randint instead of sample to avoid errors when order > 9 (sample requires unique elements) row = [random.randint(1, 9) for _ in range(order)] mat1.append(row) print("Matrix 1:") for row in mat1: print(row) # Generate random matrix 2 the same way mat2 = [] for _ in range(order): row = [random.randint(1, 9) for _ in range(order)] mat2.append(row) print("\nMatrix 2:") for row in mat2: print(row) # Initialize result matrix with zeros using list appends res_matrix = [] for _ in range(len(mat1)): # Create a row of zeros matching the number of columns in mat2 res_row = [0] * len(mat2[0]) res_matrix.append(res_row) # Perform matrix multiplication print("\nResult of Matrix Multiplication:") for p in range(len(mat1)): for q in range(len(mat2[0])): for r in range(len(mat2)): res_matrix[p][q] += mat1[p][r] * mat2[r][q] # Print the final result for res_row in res_matrix: print(res_row)
Key Notes on This Implementation:
- Random Matrix Generation: I swapped
random.sampleforrandom.randintbecausesamplerequires all elements to be unique—if yourorderis larger than 9 (the range you used: 1-9), this will throw an error.randintallows duplicate values (standard for random matrices) and works for any order size. - Result Matrix Initialization: We explicitly build
res_matrixby appending rows of zeros, which ensures we have a valid structure to store multiplication results (your original code tried to modifyres_matrixbefore initializing it, which would cause aNameError).
For Better Efficiency: Use NumPy
If you're working with larger matrices, pure Python loops will get slow quickly. NumPy is built for fast numerical operations and handles matrix multiplication natively. Here's how to do it with NumPy:
import numpy as np order = 3 # Generate random matrices (values 1-9, integer type) mat1 = np.random.randint(1, 10, size=(order, order)) mat2 = np.random.randint(1, 10, size=(order, order)) # Matrix multiplication (use the @ operator for clean syntax, or np.dot for older NumPy versions) res_matrix = mat1 @ mat2 print("Matrix 1:\n", mat1) print("\nMatrix 2:\n", mat2) print("\nResult:\n", res_matrix)
This is exponentially faster for large matrices because NumPy offloads the heavy lifting to optimized C code, avoiding Python's slow loop overhead.
内容的提问来源于stack exchange,提问作者Shahid J.

