0

I am trying to make a nxn matrix with a pattern like so: Matrix

Where if n is given it will have the nxn matrix as the output. For example if n = 5, the expected output would be:

[[ 1  0  0  0  0]
[-1  1  0  0  0]
[ 0 -1  1  0  0]
[ 0  0 -1  1  0]
[ 0  0  0 -1  1]]

Can anyone help me to device the algorithm for generating the matrix in the same pattern with n as the input? Thank you for the help

Serr
  • 11
  • This may be relevant: [How can I create a diagonal matrix with numpy?](https://stackoverflow.com/questions/58139494/how-can-i-create-a-diagonal-matrix-with-numpy) – Amadan Nov 08 '21 at 13:35

3 Answers3

2

You can get the matrix with the following code:

import numpy as np

n = 5
M = np.eye(n)
M[1:, :-1] -= np.eye(n-1)

print(M)
Yang Yushi
  • 725
  • 4
  • 20
2

The following code will solve your problem :)

def mat_fn(n, k=-1, coef=-1):
    mat = np.eye(n, n) + np.eye(n, n, k) * coef
    return mat

input:

mat_fn(5, -1, -1)

output:

   [[ 1.,  0.,  0.,  0.,  0.],
   [-1.,  1.,  0.,  0.,  0.],
   [ 0., -1.,  1.,  0.,  0.],
   [ 0.,  0., -1.,  1.,  0.],
   [ 0.,  0.,  0., -1.,  1.]]

If you want a different matrix, you could change k or the coef arguments

input:

mat_fn(5, -2, -2)

output:

[[ 1.,  0.,  0.,  0.,  0.],
   [ 0.,  1.,  0.,  0.,  0.],
   [-2.,  0.,  1.,  0.,  0.],
   [ 0., -2.,  0.,  1.,  0.],
   [ 0.,  0., -2.,  0.,  1.]]
0

For a given size, you can create an identity matrix, then insert the -1 values along the diagonal right below the main diagonal.

import numpy as np

size = 5
mat = np.identity(size, dtype=int)

for i in range(1, size):
    j = i-1
    mat[i, j] = -1

print(mat)

Output:

[[ 1  0  0  0  0]
 [-1  1  0  0  0]
 [ 0 -1  1  0  0]
 [ 0  0 -1  1  0]
 [ 0  0  0 -1  1]]
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880