7

I am trying to write a code to conduct a double summation (see pic)

enter image description here

in which; M is the subjects, N is the Trials, Yijt is the measured wave form data (3d array)

so far I have; Given Y is the data arranged as Y[subjects, trials, time]

# ranges:
I = len(Y)
J = len(Y[0])

Y_i_vals = 0

for i in range(M):
    for j in range(N):
        Y_i_vals = Y_i_vals +Y[i][j]
Yt = (1.0/(M*N)) * Y_i_vals

this doesnt seem the most effective way to do this, nor am i certain it is giving the correct result.

3 Answers3

9

If you're using numpy just do

np.mean(Y)

Also, it's good to add sample input and expected output data to your question.

If you want means for each t you can do np.mean(np.mean(a, axis=0), axis=0) , or as noted by @ophion you can shorten this to np.mean(a, axis=(0, 1)) in newer (1.71 and on) versions of NumPy.

YXD
  • 31,741
  • 15
  • 75
  • 115
  • This would compute the mean over all 3 dimensions, where the desire is to generate separate means over *M* and *N* for each *t*. (Unless *Y* in the code really represents a slice for a specific *t*.) – chepner Oct 09 '13 at 14:38
  • Updated. Adding expected input and output would make it much clearer! – YXD Oct 09 '13 at 14:39
  • 2
    In numpy 1.7.1 you can simplify this to `np.mean(a, axis=(0,1))` – Daniel Oct 09 '13 at 14:56
  • @Ophion nice, I didn't know that – YXD Oct 09 '13 at 15:02
1

To add a more general answer to your question:

You can code a double summation with the help of python list comprehension.

Yt = (1.0/(M*N)) * sum([Y[i][j] for i in range(M) for j in range(N)])
Axel
  • 2,545
  • 2
  • 18
  • 30
1

When it comes to simple double summations like in your case, it's nice to use numpy's einsum:

np.einsum('tij -> t', Y) / (M*N)
Andreas K.
  • 9,282
  • 3
  • 40
  • 45