Alcott
Alcott

Reputation: 18605

How the `along a specific axis` operation implemented?

I can sum all the elements along a specific axis, using numpy.sum, that is

>>> a = numpy.array([[1,2], [3,4]])
>>> numpy.sum(a, 1)
array([3, 7])

That is sum along row, which add elements of each column one by one.

If there are only 2 or 3 axes, I could implement it using if...elif or swith...case in C/C++, but what if there are 100 axes? How to implement it?

Upvotes: 4

Views: 203

Answers (1)

user707650
user707650

Reputation:

Numpy arrays are just one-dimensional C arrays under the hood, so stepping along a single axis is implemented by jumping through the C array in strides, the size of the stride depending on which dimension you're iterating over (smallest strides for the fastest dimension, which in Python/C would be the last dimension).

So you would have to calculate the stride corresponding to the axis, and then step through the array while calculating the sum. For each sum, you start at an offset in the array (the first would be 0), that increases with yet another step size.

If you'd like to know a bit more, you could read chapter 15 (no real need to read all the previous ones) of the guide to numpy, which starts with a section on numpy array iterations as it's done in C.

Upvotes: 2

Related Questions