Reputation: 43
I am wondering if vectorization can be applied to two vector inputs at once...
Consider the following simple function:
def f(x,y):
return(x+y,x-y)
I want to give a function like this, two vectors x=arange(3)
and y=arange(4,6)
.
My instinct is to define a,b=f(x,y)
but python tells me that these operators could not be broadcast with shapes (3) (2)
. Clearly this works if y
(or x
) were scalars.
Whats the way to do this? Is there one?
Upvotes: 2
Views: 243
Reputation: 11367
This will work fine, if the dimensions of the vectors x and y are the same. You have the following code setup:
In [16]: x=arange(3)
In [17]: x
Out[17]: array([0, 1, 2])
In [18]: y=arange(4,6)
In [19]: y
Out[19]: array([4, 5])
Obviously, x+y are not defined. Since x has 3 entities (dimensions) and y has only 2.
Consider a slight modification:
In [21]: y=arange(4,7)
In [22]: x+y
Out[22]: array([4, 6, 8])
In [23]: x-y
Out[23]: array([-4, -4, -4])
Now, x+y and x-y work as expected.
Now your function will also work fine.
In [24]: def f(x,y):
....: return (x+y,x-y)
....:
In [25]: f(x,y)
Out[25]: (array([4, 6, 8]), array([-4, -4, -4]))
Upvotes: 1