Numpy python sum over vectors of different indices

Viewed 437

I have the following formula:

enter image description here

that i have to code (C is a mtrix, y and y_star are vectors). I tried the following, according to this post: Python numpy array sum over certain indices

> def chisq02(y, y_star, C_inv):
>     indices = len(y)
>     return np.sum(np.sum(np.matmul(y[i] - y_star[i], np.matmul(C_inv, y[j]-y_star[j])) for i in indices)for j in indices)

but it returns me the error:

TypeError: 'int' object is not iterable

Obviously it does not work... Does anyone know how this could work ?

3 Answers

Your indices variable is just an integer, the length of y. But it must be a list from 0 to len(y) to loop over all indices. You can do this like so:

indices_list = range(len(y))

The range() function produces a list [0, 1, ..., len(y)-1]. Then you can loop over this list in the list comprehension.

indices = len(y) returns you an integer, so to iterate you need to use for i in range(indices).

I suspect you don't need to use np.matmul in your case because you do scalar multiplication according to your formula. I suppose C_inv[i][j] should be used instead of C_inv.

If your matrices/vectors are not arrays, first convert them to arrays:

import numpy as np

y = np.array(y)
y_star = np.array(y_star)
C_inv = np.array(C_inv)

Use this, no need for loops:

def chisq02(y, y_star, C_inv):
    return np.sum(np.matmul(np.matmul(y-y_star, C_inv), (y-y_star)))

If your y and y_star are vectors, simply this will work:

def chisq02(y, y_star, C_inv):
    return np.matmul(np.matmul(y-y_star, C_inv), (y-y_star))
Related