如何快速翻转自定义三角矩阵?基于NumPy的实现方法咨询
Question
I generated a custom triangular matrix using the following NumPy code:
import numpy as np shape=(4,8) x3=np.ones(shape) for m in range(len(x3)): step = (m * int(2)+1) #per step of 2 zeros for n in range(int(step), len(x3[m])): x3[m][n] = 0
The resulting matrix is:
array([[1., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 0.]])
I want to convert it to a row-wise flipped form like this:
array([[0., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 0., 0., 1., 1., 1.], [0., 0., 0., 1., 1., 1., 1., 1.], [0., 1., 1., 1., 1., 1., 1., 1.]])
Is there a simple way to achieve this matrix flipping operation?
Answer
Absolutely! NumPy has straightforward, efficient tools for this kind of row-wise horizontal flip. Here are two great solutions:
1. Use np.fliplr() (Recommended)
NumPy's built-in np.fliplr() function is designed specifically for flipping arrays horizontally (left to right). It's clean, readable, and optimized for performance.
import numpy as np # Your original matrix generation code shape=(4,8) x3=np.ones(shape) for m in range(len(x3)): step = (m * 2 + 1) for n in range(step, len(x3[m])): x3[m][n] = 0 # Perform horizontal flip x3_flipped = np.fliplr(x3) print(x3_flipped)
Running this will output exactly the matrix you want:
array([[0., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 0., 0., 1., 1., 1.], [0., 0., 0., 1., 1., 1., 1., 1.], [0., 1., 1., 1., 1., 1., 1., 1.]])
2. Manual Slice Flipping
If you prefer a more explicit slicing approach, you can use NumPy's array slicing syntax to reverse each row directly. This achieves the same result as np.fliplr():
x3_flipped = x3[:, ::-1]
The slice [:, ::-1] means:
:: Keep all rows::-1: Reverse the order of elements in each row (step backward through the columns)
Both methods avoid manual loops, making them far more efficient than writing custom iteration code—especially for larger matrices.
内容的提问来源于stack exchange,提问作者Jellyse

