IanHacker IanHacker - 1 year ago 48
Python Question

Is there a Python equivalent to MATLAB 'time' function?

I'm porting a MATLAB R2011b code to Python 3.5.1.
The original MATLAB code, which was written around 10 years ago, contains a 'time' function as bellow:


The output is:

debug> x
x =

-0.067000 -0.067000 -0.068000 -0.069000 -0.069000 -0.070000 -0.070000 -0.071000 -0.071000 -0.072000

debug> fsample
fsample = 10000

debug> t_x
t_x =

0.00000 0.10000 0.20000 0.30000 0.40000 0.50000 0.60000 0.70000 0.80000 0.90000

I'd like to do the same thing in Python, but I cannot find any equivalent function in Python. (The function name 'time' is too general that it's hard to search on Google.) It seems this 'time' function returns 1000/fsample (e.g., if fsample=10000, then 0.1) multiplied by the index of 'x'. Does anyone know a similar function in Python?

... Please note that this 'time' function is different from the 'time' function introduced in MATLAB R2014b:

Answer Source

It should be simple enough to implement a similar function.

For numpy arrays

import numpy as np
def time(x, fsample):
    return np.linspace(0, (1000/fsample)*(len(x) - 1), num=len(x))

For simple python lists

def time(x, fsample):
    return [i*(1000/fsample) for i in range(len(x))]