1

I want to create an array of elements. I can do it using a loop, but i want to know if there is another way, like an numpy function or something to do this in less timme.

this is what i want to do:

def no_loops(y):


   mat = []
   for i in range(5012):
       mat.append(y[i])

   fun = funcion_a(mat)

   return fun

The y array is empty. The elements of the array are the solutions of an equation system that scipy will solve. I want to change the for loop for something faster.

1 Answers1

0

If you want a new array of a certain size, and want to ignore the very confusing y from your sample code, you could do something like this:

def no_loops():
    # Create an array of length 5012, all elements of which are zero.
    return funcion_a(numpy.zeros(5012))

You could also use numpy.empty in this case, but I prefer the determinism of numpy.zeros.

If you want to copy the data in y, you could explicitly copy using numpy.array:

def no_loops(y):
   return funcion_a(numpy.array(y[:5012]))

You could also investigate using numpy.asanyarray if you need to support subclasses of numpy.array. See: Numpy - array vs asarray

NicholasM
  • 4,557
  • 1
  • 20
  • 47