Python NumPy技术求助:如何将指定数值填入4×4矩阵主对角线
Hey there! Let's get your matrix working exactly how you want it. Your current code is modifying off-diagonal positions, which isn't what we need for the main diagonal. Here are a couple of straightforward ways to fix this:
Method 1: Adjust Your Existing Zero Matrix
Since you already created a 4×4 zero matrix with ar.zeros((4,4)), you can directly target the main diagonal using index pairs. The main diagonal consists of positions where the row index equals the column index (like (0,0), (1,1), (2,2), (3,3)).
Add this line to your code to assign values 1-4 to those positions:
import numpy as ar x = ar.zeros((4, 4)) # Target main diagonal indices and assign the desired values x[range(4), range(4)] = [1, 2, 3, 4] print(x)
Running this will give you the exact output you're looking for:
[[1. 0. 0. 0.]
[0. 2. 0. 0.]
[0. 0. 3. 0.]
[0. 0. 0. 4.]]
Method 2: Use NumPy's Built-in diag Function
For an even more concise approach, NumPy has a diag function that creates a diagonal matrix directly. You just pass in the list of values you want on the main diagonal:
import numpy as ar # Create the diagonal matrix in one step x = ar.diag([1, 2, 3, 4]) print(x)
This produces the same result, skipping the step of creating a zero matrix first.
The core idea here is that the main diagonal is accessed when row and column indices match—using range(4) for both rows and columns lets you target those exact positions effortlessly.
内容的提问来源于stack exchange,提问作者Great Dreamer

