Python code to create a diagonal matrix with 1 above the main diagonal

I would like to write a python function that creates a null matrix of size n by n, which has 1 for all elements above the main diagonal.

Here is my code:

def funtest(n):
    for i in range(0,n-2):
        s = (n,n)
        Y = zeros(s)
        Z = Y
        Z[i,i+1]=1          
return Z

But the result gives only 1 in the (n-1, n-2) matrix element.

I am stuck and I really think my code is correct and has no idea where the error is. And how can I fix this? Can anybody help?

Thank.

+4
source share
3 answers

A function numpy.diagcan do just that:

import numpy as np
print( np.diag(np.ones(4), 1) )

With the second argument ( 1), the offset for the diagonal. He gives:

array([[ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.]])
+8
source

, ?

np.tri* :

In [395]: np.triu(np.ones((5,5),int),1)
Out[395]: 
array([[0, 1, 1, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0]])

tri

In [399]: np.tril(np.triu(np.ones((5,5),int),1),1)
Out[399]: 
array([[0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0]])

, np.diag.:)

In [404]: np.diagflat(np.ones(4,int),1)
Out[404]: 
array([[0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0]])
+3

. zeros , :

def funtest(n):
    s = (n,n)
    Y = zeros(s)
    for i in range(0,n-1):
        Y[i,i+1]=1          
    return Y

, n-1, n-2 ( 1s 1!). :

funtest(5)

array([[ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.]])

, . Swier, numpy builtin np.diag(np.ones(n-1),1).

+2

All Articles