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?
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])