Python Forum

Full Version: about Numpy indexing.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
a = np.arange(25).reshape(5, 5)
a
Output:
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])
np.diag(a, k = -1)
Output:
array([ 5, 11, 17, 23])
np.diag(a, k = -2)
Output:
array([10, 16, 22])
How to do like below:
Use feature of np.diag(), indexing specific elements then multiply 10?

a = np.full((5, 5), 1)
Output:
array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
want:
Output:
array([[1, 1, 1, 1, 1], [10, 1, 1, 1, 1], [1, 10, 1, 1, 1], [1, 1, 10, 1, 1], [1, 1, 1, 10, 1]])
Output:
array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [10, 1, 1, 1, 1], [1, 10, 1, 1, 1], [1, 1, 10, 1, 1]])
For the first matrix (use the same strategy for the other one)

Paul
import numpy as np
n = 5
M = np.ones( (n,n) )
i = np.arange(1,n)
M[i,i-1] = 10*M[i,i-1]

print(f'M = {M}')
Output:
M = [[ 1. 1. 1. 1. 1.] [10. 1. 1. 1. 1.] [ 1. 10. 1. 1. 1.] [ 1. 1. 10. 1. 1.] [ 1. 1. 1. 10. 1.]]