pythonnumpymatrixlinear-algebra

Numpy - Declare a specific nx1 array


I'm using numpy in python , in order to create a nx1 matrix . I want the 1st element of the matrix to be 3 , the 2nd -1 , then the n-1 element -1 again and at the end the n element 3. All the in between elements , i.e. from element 3 to element n-2 should be 0. I've made a drawing of the mentioned matrix , is like this : enter image description here

I'm fairly new to python and using numpy but seems like a great tool for managing matrices. What I've tried so far is creating the nx1 array (giving n some value) and initializing it to 0 .

import numpy as np

n = 100

I = np.arange(n)

matrix = np.row_stack(0*I)

print("\Matrix is \n",matrix)

Any clues to how i proceed? Or what routine to use ?


Solution

  • Probably the simplest way is to just do the following:

    import numpy as np
    
    n = 10
    a = np.zeros(n)
    
    a[0] = 3
    a[1] = -1
    a[len(a)-1] = 3
    a[len(a)-2] = -1
    
    >>print(a)
    output: [ 3. -1.  0.  0.  0.  0.  0.  0.  -1. 3.]
    

    Hope this helps ;)