如何生成含指定数量随机位置1的0/1矩阵?咨询10x10矩阵可行性
Absolutely achievable! This is a common task in data manipulation and simulation, and it’s straightforward to implement in most programming languages. Let’s use Python as our example—you can adapt the logic to other languages like R, MATLAB, or Julia easily.
First, we’ll make an all-zero matrix where you can adjust the dimensions (rows and columns) as needed. For your 10x10 example, we’ll set rows=10 and cols=10, but you can swap those numbers for any size you want.
Using NumPy (the go-to for numerical matrices)
NumPy simplifies matrix initialization with a single line:
import numpy as np # Define adjustable dimensions rows = 10 cols = 10 # Initialize an all-zero integer matrix zero_matrix = np.zeros((rows, cols), dtype=int)
Pure Python approach (no external libraries)
If you prefer avoiding third-party tools, use nested lists to build the matrix:
rows = 10 cols = 10 # Create a 2D list filled with zeros zero_matrix = [[0 for _ in range(cols)] for _ in range(rows)]
Next, we need to pick N distinct positions (no overlapping 1s) and set those elements to 1. For your request, N=5, but this number is also fully adjustable.
Using NumPy (simpler and faster)
NumPy has built-in functions to generate unique random indices. We’ll flatten the matrix’s index space, pick 5 unique entries, then map them back to row-column pairs:
# Number of 1s to place (adjust this value as needed) num_ones = 5 # Generate unique flattened indices (no repeats) flat_indices = np.random.choice(rows * cols, size=num_ones, replace=False) # Convert flattened indices to (row, column) coordinates row_indices, col_indices = np.unravel_index(flat_indices, (rows, cols)) # Set the selected positions to 1 zero_matrix[row_indices, col_indices] = 1 # Print the final matrix print(zero_matrix)
Pure Python approach
If you’re sticking to base Python, generate unique (row, column) tuples manually to avoid duplicates:
import random num_ones = 5 unique_positions = set() # Generate unique positions until we have enough while len(unique_positions) < num_ones: row = random.randint(0, rows - 1) col = random.randint(0, cols - 1) unique_positions.add((row, col)) # Update the matrix with 1s for row, col in unique_positions: zero_matrix[row][col] = 1 # Print the result row by row for row in zero_matrix: print(row)
Each run will produce different positions for the 1s because the random number generator uses a new seed by default. If you ever need to reproduce the exact same matrix (for testing), you can lock the seed at the start:
# For NumPy np.random.seed(42) # For pure Python random.seed(42)
Just remove the seed line when you want fresh random positions again.
内容的提问来源于stack exchange,提问作者Danielle

