1

I am generating random variables in my array: np.random.rand(5,3,20)

How can I create the same shape and size but sequentially between 0 and 1?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
jacky
  • 524
  • 1
  • 5
  • 15

3 Answers3

3

Create evenly spaced numbers over a specified interval using linspace and then reshape to shape required as follows:

np.linspace(0, 1, 300).reshape(5, 3, 20)

Note:

'The new shape should be compatible with the original shape'

So let's say, for np.linspace(0, 1, t).reshape(x, y, z) the condition that should be met is t = x*y*z

JkShaw
  • 1,927
  • 2
  • 13
  • 14
  • when I run `np.linspace(0, 1, 300).reshape(5,5,20)` , i get this error: `ValueError: total size of new array must be unchanged` – jacky May 10 '17 at 12:37
  • `5*3*20 = 300`, where as `5*5*20 = 500`, you need to provide `shape` whose total elements must be same, that is for `np.linspace(0, 1, t).reshape(x, y, z)` the condition that should be met `t = x*y*z` – JkShaw May 10 '17 at 12:40
2

Just use:

np.linspace(0, 1, num=5).reshape((5, 3))

and set the num param to implicitly define how big needs to be your step.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
FrankBr
  • 886
  • 2
  • 16
  • 37
  • i get this error `ValueError: total size of new array must be unchanged` and where is the value `20` gone? – jacky May 10 '17 at 12:41
1

Another option:

#start:stop:stepj inside np.r_ is interpreted as np.linspace(start, stop, step, endpoint=1) inside of the brackets
np.r_[0:1:300j].reshape(5,3,20)
Allen Qin
  • 19,507
  • 8
  • 51
  • 67