Home > Net >  using arrays of different sizes within a function
using arrays of different sizes within a function

Time:12-01

I'm trying to write a function that will take a set of arguments from the rows of a 2d array and use them in conjunction with all the elements of a longer 1d array:

x = np.linspace(-10,10,100)
abc = np.array([[1,2,1],
      [1,3,5],
      [12.5,-6.4,-1.25],
      [4,2,1]])


def quadratic(a, b, c, x):
    return a*(x ** 2)   b*x   c


y = quadratic(abc[:,0], abc[:,1], abc[:,2], x)


But this returns:

operands could not be broadcast together with shapes (4,) (100,)

When I manually enter the a, b and c values, I get a 100-element 1d array, so I would expect this to return a (4,100) array. What gives?

CodePudding user response:

In numpy the operation x * y is performed element wise where one or both values can be expanded to make them compatible. This is called broadcasting. In the example above your arrays have different dimensions (100,0) and (4,3), hence the error.

When multiplying matrixes you should be using dot instead.

import numpy as np

x = np.linspace(-10,10,100)
abc = np.array([[1,2,1],
      [1,3,5],
      [12.5,-6.4,-1.25],
      [4,2,1]])

np.dot(x, abc[:,0])

CodePudding user response:

abc[:, i] is of shape (4). You need it to be of shape (4, 1) to broadcast against x of shape (100) to produce your desired (4, 100) output---so you will need to do abc[:, i, None] to add that extra dimension.

The following should work:

y = quadratic(abc[:, 0, None], abc[:, 1, None], abc[:, 2, None], x)
  • Related