3

I want to do linspace to an array. Just like following:

a = np.array([2, 4, 6])
b = vectorize(np.array)(0, a, 5)

I would like something back that looks like:

b = [[0, 0.5, 1, 1.5, 2]
     [0, 1, 2, 3, 4]
     [0, 1.5, 3, 4.5, 6]]

This is my code:

import numpy as np
a = np.arange(1001)
c = np.vectorize(np.linspace)(0, a, 101)
print(c)

It shows that: ValueError: setting an array element with a sequence. Is there any method to do this in numpy without for loop?

jiangniao
  • 125
  • 1
  • 2
  • 11

1 Answers1

5

Build your own:

def vlinspace(a, b, N, endpoint=True):
    a, b = np.asanyarray(a), np.asanyarray(b)
    return a[..., None] + (b-a)[..., None]/(N-endpoint) * np.arange(N)
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Thanks. Why did you use np.asanyarray rather than np.array? – jiangniao Mar 06 '17 at 05:46
  • @jiangniao it doesn't force a copy and it leaves `ndarray` subclasses alone, so it's the least invasive. – Paul Panzer Mar 06 '17 at 05:54
  • Do you mind explaining how this works? – Carpetfizz Mar 15 '18 at 20:00
  • 1
    @Carpetfizz It adds one new dimension to the end of the what `a` and `b` are broadcast to (the `None` after `...` does that). The sequence is generated by `arange` and occupies that new dimension. It is scaled with the difference of endpoints (`b-a`) divided by thet number of points (`N-endpoint`) and based on the left endpoint `a`. Since we are only using basic numpy operations everything is vectorized out of the box. – Paul Panzer Mar 15 '18 at 21:27