You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何快速翻转自定义三角矩阵?基于NumPy的实现方法咨询

How to Flip a Custom Triangular Matrix Row-Wise in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:43:23