Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab to Python conversion of rand()

In Matlab I have the following:

duration = 20
n=5
times = rand(1,n)*duration;

The variable "times" gives a 1-by-n matrix, which is populated with random numbers between 0 and 1, then multiplied by 20. This will result in a set of 5 numbers between 0 and 20.

Now I want to achieve the same in Python, what would be the equivalent? I tried the following:

times = random.uniform(1,durations,n)  %% or times = random.uniform(1,20,5)

But I get this error:

TypeError: uniform() takes exactly 3 arguments (4 given)

which does not make sense to me, because I only seem to have given it 3 arguments.

like image 506
Spica Avatar asked Oct 26 '25 06:10

Spica


1 Answers

random.uniform only accepts the upper and lower bounds of your random numbers. You will want to call random.uniform n times to create a list of random values.

values = [random.uniform(0, 20) for _ in range(5)]

Alternately, you could use numpy.random.rand to do this similarly to MATLAB and the function will return a numpy array.

import numpy as np
values = np.random.rand(1, 5) * 20

If you are converting much code from MATLAB to Python, numpy is recommended over using standard datatypes due to it's computational speed and similar behavior to MATLAB.

like image 57
Suever Avatar answered Oct 28 '25 19:10

Suever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!