James Flash
James Flash

Reputation: 548

Trouble with updating array elements in a for-loop

I want to redefine array elements in my function roll

roll_current = 0

def roll(t):
    global roll_current

    # Generate array of the same numbers
    roll_current_ =  np.full((len(t)), roll_current)

    delta_roll_ = 0.1 - np.exp(-t)
    diff_ = roll_current_ - delta_roll_     

    # Update roll_current_ array
    for i, x in enumerate(roll_current_):
        if diff_[i]>0:
            roll_current_[i] = x - abs(diff_[i]) # x is equal to roll_current_[i] 
        elif diff_[i]<0:
            roll_current_[i] = x + abs(diff_[i]) 

    # Save value for the last time step
    roll_current = roll_current_[-1] # Scalar

    return roll_current_

But if I use -= or +=assignment or the code above then roll_current_ array doesn't change and the following lines

t = np.linspace(0,4,10)
roll(t)

give array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

What is wrong?

Upvotes: 1

Views: 38

Answers (2)

markuscosinus
markuscosinus

Reputation: 2267

I found the problem in your code:

The fill method fills an array with the value of roll_current which is an integer. Thus the array will also be of type int. Then in the for-loop all the values you are trying to set are between -1 and 1 and are therefor rounded to zero. To solve the problem, change this line

roll_current_ =  np.full((len(t)), roll_current)

to this

roll_current_ =  np.full((len(t)), roll_current, dtype = np.float)

Alternatively you could just initialize roll_current like this:

roll_current = 0.

Upvotes: 1

Felix Martinez
Felix Martinez

Reputation: 512

If you do a print of roll_current_ = np.full((len(t)), roll_current) output:

[0 0 0 0 0 0 0 0 0 0]

probably you doesnt want this.

Please dont use globals if you can avoid it, why not def roll(t, roll_current)?

At for loop dont update the same array you are iterating, instead build another array appending the new items.

Upvotes: 0

Related Questions