Practice2 solution
中文版:练习 2 参考答案
Import NumPy using np as an alias
import numpy as np- Create a 6×6 matrix X (with all elements being unique, e.g., 1 to 36), and extract the 3rd and 5th columns from X to form a new matrix Y.
# Step 1: Create a 6x6 matrix with unique elements (e.g., 1 to 36)
X = np.arange(1, 37).reshape(6, 6) # Generates numbers 1 to 36 in 6x6 shape
print("Matrix X (6x6):")
print(X)
# Step 2: Extract the 3rd and 5th columns (indices 2 and 4 in 0-based indexing)
Y = X[:, [2, 4]] # Select columns 2 and 3
print("\nMatrix Y (6x2, 3rd & 4th columns of X):")
print(Y)- Now we have an array X_1 of shape 6x6, predict the result of X+X_1
X_1=np.full((6, 6), 3.14)Z=X+X_1
print(Z)- Predict the result of X + Y, and use code to perform the corresponding calculation
Z=X+Y # is this correct?- Calculate the maximum value in each row of X, and the minimum value in each column of Y.
# Max in each row of X
row_max_X = np.max(X, axis=1)
print("Max per row of X:", row_max_X)
# Min in each column of Y
col_min_Y = np.min(Y, axis=0)
print("Min per column of Y:", col_min_Y)- Create an 8×8 array filled with zeros. Randomly select 25 positions and fill them with random numbers greater than 0 using ‘np.random.uniform’. Print the resulting matrix W.
# Step 1: Create an 8x8 array of zeros
W = np.zeros((8, 8))
# Step 2: Randomly select 25 unique positions (indices)
positions = np.random.choice(64, 25, replace=False) # 8x8=64 total positions
rows = positions // 8 # Convert flat indices to row indices
cols = positions % 8 # Convert flat indices to column indices
# Step 3: Fill selected positions with random numbers > 0
W[rows, cols] = np.random.uniform(0.1, 10.0, size=25) # Random numbers in (0.1, 10.0)
# Print the resulting matrix W
print("Matrix W (8x8 with 25 random non-zero entries):")
print(W)- Calculate the average value of the elements in the matrix and store it in a variable named mean_W. Replace all the zeros in W with the value of mean_W.
# Calculate the mean of all elements in W (excluding zeros if needed)
mean_W = np.mean(W) # If zeros should be included in the mean calculation
# OR, if zeros should be excluded:
# mean_W = np.mean(W[W != 0]) # Only average non-zero elements
# Replace zeros with mean_W
W_no_zeros = np.where(W == 0, mean_W, W) # Creates a new matrix
# Alternatively, modify W in-place:
# W[W == 0] = mean_W
print("Mean value (mean_W):", mean_W)
print("\nMatrix W with zeros replaced by mean_W:")
print(W_no_zeros)- Replace all values in the matrix that are smaller than mean_W with -1, and print how many -1 values are in the matrix.
# Calculate mean_W (as previously defined)
mean_W = np.mean(W)
# Replace values < mean_W with -1
W_replaced = np.where(W < mean_W, -1, W)
# Count the number of -1 values
count_minus_1 = np.sum(W_replaced == -1)
# Print results
print(f"Mean value (mean_W): {mean_W:.4f}")
print(f"Number of -1 values: {count_minus_1}")
print("\nMatrix after replacement:")
print(W_replaced)- Compute the transpose of matrix W and store it in Z. Combine W and Z to form a 3-dimensional matrix V, and then flatten Z to get a new 1-dimensional array U.
# Step 1: Compute transpose of W and store in Z
Z = W.T # or np.transpose(W)
# Step 2: Combine W and Z to form a 3D matrix V (shape: 2 x rows x cols)
V = np.array([W, Z]) # Stack W and Z along a new axis
# Step 3: Flatten Z to get a 1D array U
U = Z.flatten() # or Z.ravel()
# Print results
print("Transpose Z:")
print(Z)
print("\n3D Matrix V (shape: {}):".format(V.shape))
print(V)
print("\nFlattened array U:")
print(U)- Find the third largest value in matrix W, denoted as Max3. Then, obtain a Boolean matrix B from W where all elements greater than or equal to Max3 are marked as True, and the rest as False.
# Step 1: Flatten W and find the third largest value (Max3)
flat_W = W.flatten()
unique_sorted = np.sort(np.unique(flat_W)) # Sort unique values in ascending order
Max3 = unique_sorted[-3] if len(unique_sorted) >= 3 else unique_sorted[-1] # Handle edge cases
# Step 2: Create Boolean matrix B
B = W >= Max3
# Print results
print(f"Third largest value (Max3): {Max3}")
print("\nBoolean matrix B:")
print(B)- Print the elements in Z that correspond to the True positions in B and calculate their average.
# Step 1: Get elements in Z where B is True
selected_elements = Z[B]
# Step 2: Calculate the average of these elements
average_selected = np.mean(selected_elements) if selected_elements.size > 0 else np.nan
# Print results
print("Elements in Z corresponding to True positions in B:")
print(selected_elements)
print(f"\nAverage of these elements: {average_selected}")- Combine A and B into a 2x4 matrix C. Then, combine A and B into an 4x2 matrix D. Finally, print out the elements of C row by row., print out the elements of D column by column.
# Combine into C (2x4) by horizontal stacking
C = np.concatenate((A, B), axis=1)
# Combine into D (4x2) by vertical stacking
D = np.concatenate((A, B), axis=0)
print(C)
print(D)# Print C row by row
print("Matrix C (row by row):")
for row in C:
print(row)
# Print D column by column
print("\nMatrix D (column by column):")
for col_idx in range(D.shape[1]): # Iterate over the list colomn index
column = D[:, col_idx] # get the current column
print(column)