Home > Blockchain >  Changing the value of alternated rows of a vector in Python
Changing the value of alternated rows of a vector in Python

Time:01-19

Suppose I have the following NumPy array in python:

V = 2*np.ones([7,1]); V[0]=1; V[6]=1

Which will give me:

V = ([[1.],
      [2.],
      [2.],
      [2.],
      [2.],
      [2.],
      [1.],])

How can I change only the terms with odd indexes? For example, change the terms on the rows 1,3 and 5, to 4 (counting the first one as row 0) like the one below:

V = ([[1.],
      [4.],
      [2.],
      [4.],
      [2.],
      [4.],
      [1.],])

Is there a simpler way than to start a loop and check every element one by one? In this problem, I adopted a 7x1 column vector, but I want to solve for the general case of an Nx1 array. Thank you in advance!

CodePudding user response:

You can simply use slicing operator like

V[1::2] = 4

this mean start from the second entry, 1, and takes steps by 2 from there.

CodePudding user response:

You can use enumerate() on V:

for i,j in enumerate(V):
    if i % 2 == 1:
        V[i] = 4

Output:

array([[1.],
       [4.],
       [2.],
       [4.],
       [2.],
       [4.],
       [1.]])
  •  Tags:  
  • Related