Array passed using numpy

How to write the following loop using an implicit Python loop?

def kl(myA, myB, a, b): lots of stuff that assumes all inputs are scalars x, y = meshgrid(inclusive_arange(0.0, xsize, 0.10),\ inclusive_arange(0.0, ysize, 0.10)) for j in range(x.shape[0]): for i in range(x.shape[1]): z[j, i] = kl(x[j, i], y[j, i]) 

I want to do something like

 z = kl(x, y) 

but it gives:

 TypeError: only length-1 arrays can be converted to Python scalars 
+2
python numpy
source share
2 answers

The feature you are asking for exists only in Numpy, and it is called a broadcast array , not an implicit loop. A function that passes a scalar operation on an array is called a universal function or ufunc. Many basic Numpy functions are of this type.

You can use numpy.frompyfunc to convert an existing kl function to ufunc.

 kl_ufunc = numpy.frompyfunc(kl, 4, 1) ... z = kl_ufunc(x + 1.0, y + 1.0, myA, myB) 

Of course, if you want, you can call ufunc kl instead of kl_ufunc , but the original definition of kl will be lost. This may be good for your purposes.

+5
source share

Here you can find the video:

http://showmedo.com/videotutorials/video?name=10370070&fromSeriesID=1037

Note that this is part of a tutorial series that discusses a wide range of numpy issues.

Just FYI.

+1
source share

All Articles