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

Python可变维度矩阵构建:能否基于np.eye与循环实现特定方阵?

Custom n-order Matrix Using np.eye() and Loops

Absolutely! You can definitely build this specific n-order matrix starting with np.eye(n) and adding a straightforward loop to populate the middle rows. Let’s walk through how to do this step by step:

Step 1: Initialize the base matrix

Start with NumPy’s identity matrix—it already sets the first element of the first row and the last element of the last row to 1, which matches your desired structure perfectly. No need to manually set those values!

import numpy as np

# Define your parameters
n = 5  # Replace with your desired matrix order
a = 2  # Replace with your value for a
b = 3  # Replace with your value for b
c = 4  # Replace with your value for c

# Start with the identity matrix as the base
mat = np.eye(n)

Step 2: Populate the middle rows with a loop

The rows we need to modify are the ones between the first and last (indices 1 to n-2, since Python uses 0-based indexing). For each of these rows, we’ll set the three consecutive elements to a, b, and c respectively:

# Loop through all middle rows
for i in range(1, n-1):
    mat[i, i-1] = a  # Position left of the main diagonal
    mat[i, i] = b    # Main diagonal position
    mat[i, i+1] = c  # Position right of the main diagonal

Step 3: Verify the result

For n=5, running this code will produce exactly the matrix you described:

[[1. 0. 0. 0. 0.]
 [2. 3. 4. 0. 0.]
 [0. 2. 3. 4. 0.]
 [0. 0. 2. 3. 4.]
 [0. 0. 0. 0. 1.]]

This approach keeps things simple, leverages the identity matrix for the edge cases, and uses a loop to handle the repetitive pattern in the middle rows. You can easily adjust n, a, b, and c to fit your specific needs.

内容的提问来源于stack exchange,提问作者Andrew98

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:46:56