Home > Enterprise >  for loop, append data
for loop, append data

Time:01-24

I have a variable x of size x=(8000,2). I want to select the value at each 100 location, so, (0,99,198,297...), and apply a second loop which multiplies that value 100 times, and save it in a list, thus at the end of the 2 loops, I have a variable of size (8000,2)

A functional code is:

num_data = 8000

x_data = []
x_data.append(np.random.uniform(high=-1, low=1,size=(num_data, 2)))
x_data=np.asarray(x_data)



K= np.random.uniform(high=-1, low=1, size=(2, 2))

ys=[Obs_x0]

for i in range (80):
    Obs_x0 = x_data[:,i*99]
   
    traj=[Obs_x0]
    for j in range(99):
        Obs_x0 = np.matmul(Obs_x0, K)    
        traj.append(Obs_x0)
        
        ys.append(traj)
        
ys=np.asarray(ys)
print(ys.shape)



When I run it, the shape of ys(7921,) when it should be ys(8000,2). I think that the problem is that the code is not appending Obs_x0 from the first loop

Any ides how to solve it>

CodePudding user response:

Leave ys empty before the for loop -> ys=[].

the range in your second loop is faulty: range(99) counts from 0-98. what you want is probably range(100) which counts from 0-99.

your final code should look like this:

import numpy as np

num_data = 8000

x_data = []
x_data.append(np.random.uniform(high=-1, low=1, size=(num_data, 2)))
x_data = np.asarray(x_data)
print(x_data.shape)
K = np.random.uniform(high=-1, low=1, size=(2, 2))

ys = []

for i in range(80):
    Obs_x0 = x_data[:, i * 99]

    traj = [Obs_x0]
    for j in range(100):
        Obs_x0 = np.matmul(Obs_x0, K)
        ys.append(Obs_x0)

ys = np.asarray(ys)
print(ys.shape)
  • Related