I am learning how to code and wondered how to take the mean without using a builtin function (I know these are optimized and they should be used in real life, this is more of a thought experiment for myself).
For example, this works for vectors:
def take_mean(arr):
sum = 0
for i in arr:
sum += i
mean = sum/np.size(arr)
return mean
But, of course, if I try to pass a matrix, it already fails. Clearly, I can change the code to work for matrices by doing:
def take_mean(arr):
sum = 0
for i in arr:
for j in i:
sum += i
mean = sum/np.size(arr)
return mean
And this fails for vectors and any >=3 dimensional arrays.
So I'm wondering how I can sum over a n-dimensional array without using any built-in functions. Any tips on how to achieve this?
for i in arr.flatten(). Note that Numpy do no use a naive sum like this which is known not to be numerically stable for large FP-based arrays. Also note that this code will be slow like hell compared to Numpy vectorized functions (implemented in C). If you do not want to useflatten, then you can do that using recusive function doing a per-axis reduction and operating with views but this will be significantly more complex and even slower.