如何对5×2矩阵按第二列排序并保持列元素的对应关联?
Hey there! The key fix here is to sort the entire rows of your matrix based on the values in the second column—instead of just sorting the second column alone. That way, each row's pair of values stays linked. Here's how to do this in a few common tools:
Python (using NumPy)
NumPy simplifies this with argsort(), which returns the indices that would sort the target column. You can use those indices to reorder the whole matrix:
import numpy as np # Your original 5x2 matrix matrix = np.array([ [1, 0.25], [2, 0.125], [3, 0.0625], [4, 0.0625], [5, 0.5] ]) # Get indices that sort the second column in DESCENDING order # The "-" reverses the default ascending sort to descending sort_indices = np.argsort(-matrix[:, 1]) # Reorder the entire matrix using these indices sorted_matrix = matrix[sort_indices] print(sorted_matrix)
Output:
[[5. 0.5 ] [1. 0.25 ] [2. 0.125 ] [3. 0.0625] [4. 0.0625]]
Python (using Pandas)
If you're working with tabular data, Pandas is even more intuitive—just sort the DataFrame by the second column:
import pandas as pd # Create a DataFrame from your matrix data df = pd.DataFrame({ 'col1': [1, 2, 3, 4, 5], 'col2': [0.25, 0.125, 0.0625, 0.0625, 0.5] }) # Sort by col2 in descending order, preserving row pairs sorted_df = df.sort_values(by='col2', ascending=False) print(sorted_df)
Output:
col1 col2 4 5 0.5000 0 1 0.2500 1 2 0.1250 2 3 0.0625 3 4 0.0625
MATLAB
MATLAB has a built-in sortrows() function that sorts the entire matrix based on specified columns directly:
% Your original matrix matrix = [1 0.25; 2 0.125; 3 0.0625; 4 0.0625; 5 0.5]; % Sort rows by the second column in descending order % The "-2" tells MATLAB to sort by column 2 in reverse order sorted_matrix = sortrows(matrix, -2); disp(sorted_matrix);
Output:
5.0000 0.5000 1.0000 0.2500 2.0000 0.1250 3.0000 0.0625 4.0000 0.0625
R
In R, use order() to get the sorted indices, then reindex your matrix to preserve row pairs:
# Original matrix (columns are filled sequentially) matrix <- matrix(c(1,2,3,4,5, 0.25,0.125,0.0625,0.0625,0.5), ncol=2) # Get indices for descending sort on the second column sort_indices <- order(-matrix[,2]) # Reorder the matrix rows using these indices sorted_matrix <- matrix[sort_indices, ] print(sorted_matrix)
Output:
[,1] [,2] [1,] 5 0.5000 [2,] 1 0.2500 [3,] 2 0.1250 [4,] 3 0.0625 [5,] 4 0.0625
Quick Summary
The core idea across all tools is:
- Get the indices that would sort the second column (in your desired order, descending here)
- Use those indices to reorder the entire matrix's rows, ensuring each row's two values stay paired together.
内容的提问来源于stack exchange,提问作者Γιάννης Γιαννάκος

