Search code examples
pythonnumpy

numpy add array of constants to array of matrixes


Consider a numpy array X with m elements. Each element it's itself a numpy matrix of a generic (but, more importantly, fixed shape (n0, n1, ..., n) so that X shape is (m, n0, n1, ..., n). Now, take a list of m (different) scalar, let's say something like this:

c = np.arange(m)

c and X have the same number of elements: c is an array of m scalar, while X it's an array of m matrixes.

I would like to add to every elements of X[i] the constant c[i]

for i in range(m):
    X[i] += c[i]

is it possible to perform this calculation without the for loop? Something like X+c (but ofc it does not work)

Thank you for your help

EDIT: Code example

import numpy as np

m = 3
X = np.arange(m*4*3*6*5*7).reshape((m, 4, 3, 6, 5, 7))
c = np.arange(m)
for i in range(m):
    X[i] += c[i]

Solution

  • For this I assume that each element m is the same size, for example:

    X = np.array([[1, 2, 3, 4],[2, 3, 4, 5]])
    m = X.shape[0]
    c = np.arange(m) + 1 # np.array([1, 2])
    

    Now you can use a transpose of X

    (X.T + c).T
    array([[2, 3, 4, 5],
           [4, 5, 6, 7]])
    

    And for your code it also works, for example:

    X = np.arange(m*4*3*6*5*7).reshape((m, 4, 3, 6, 5, 7))
    X[2,0,0,0,0,0]
    >>> array([5040, 5041, 5042, 5043, 5044, 5045, 5046])
    X = (X.T + c).T
    X[2,0,0,0,0,0]
    >>> array([5042, 5043, 5044, 5045, 5046, 5047, 5048])