Home > database >  Python making a large N x N matrix
Python making a large N x N matrix

Time:11-09

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

CodePudding user response:

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)

CodePudding user response:

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.]]

CodePudding user response:

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]]
  • Related