2

I'm new to Python, but I'm trying to learn. I'm trying to recreate a Matlab for loop in Python. The Matlab for loop looks like this:

for i = 2:(L-1)
    Acceleration_RMT5_x(i-1) = (RMT5(i+1,1)-2*RMT5(i,1)+RMT5(i
    1,1))/(1/FrameRate)^2;
end

The datatype is float64, and is a 288x1 vector. My Python so far is:

for i in RMT5x:

  Acceleration_RMT5x = RMT5x[i+1] -2*RMT5x[i] +RMT5x[i-1]/(1/250)^2)

This gives me "invalid syntax".

What do I need to fix to resolve this error?

Joe
  • 457
  • 5
  • 18
MichaelSK
  • 39
  • 5

2 Answers2

2

To raise something to a power in Python you need ** not ^

Also you are looping through the values of RMT5x but you are trying to use the value (i) as an index. Instead you want to loop through the index.

Acceleration_RMT5x = list()

for i in range(1, len(RMT5x)-1):
    Acceleration_RMT5x.append(RMT5x[i+1] -2*RMT5x[i] +RMT5x[i-1]/(1./250)**2)
Suever
  • 64,497
  • 14
  • 82
  • 101
  • You still have the OP's parenthesis error, and your loop will fail because the i+1 will try to read an index which doesn't exist. (I'm also not convinced that the OP doesn't want to modify an existing ndarray in place, but that's hard to be sure of.) – DSM Apr 21 '16 at 18:02
  • It is better to use `enumerate(RMT5x)` in this situation. – TheBlackCat Apr 22 '16 at 13:35
  • @TheBlackCat Except it's not because the user needs to access the previous and next entries of `RMT5x`. Using `enumerate` would not allow for this. – Suever Apr 22 '16 at 20:21
0

I would use a list comprehension:

import numpy as np
Acceleration_RMT5x = [np.power( (RMT5(i+1,1)-2*RMT5(i,1)+RMT5(i-1,1))/(1/FrameRate), 2)]
user69453
  • 1,279
  • 1
  • 17
  • 43