Ian Chung
Ian Chung

Reputation: 19

How to write a vector function to apply operation f(x,y)?

scalar_function can only handle scalar input, we could use the function np.vectorize() turn it into a vectorized function. Note that the input argument of np.vectorize() should be a scalar function, and the output of np.vectorize() is a new function that can handle vector input.

Please write a vector function vector_function, which will apply the operation 𝑓(𝑥,𝑦) defined above element-wisely with input vectors with same dimension x and y.

So for the scalar, I got :

def scalar_function(x, y):
    
    if x <= y:
        return x*y
    else:
        return x/y

For the vector function I have :

def vector_function(x, y):

    vfunc = np.vectorize(scalar_function, otypes = [float])
    return vfunc

From here on I am stuck.

Upvotes: 0

Views: 2058

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 102529

You can rewrite the function in a vectorized manner like below:

def scalar_function(x, y):
    print('x=\n', x, '\n')
    print('y=\n', y, '\n')
    return x * y ** (2 * (x <= y) - 1)

And you could try for example:

np.random.seed(0)
x = np.random.rand(2, 5)
y = np.random.rand(2, 5)
print(scalar_function(x, y))

which shows

x=
 [[0.5488135  0.71518937 0.60276338 0.54488318 0.4236548 ]
 [0.64589411 0.43758721 0.891773   0.96366276 0.38344152]]

y=
 [[0.79172504 0.52889492 0.56804456 0.92559664 0.07103606]
 [0.0871293  0.0202184  0.83261985 0.77815675 0.87001215]]

array([[ 0.43450939,  1.35223338,  1.06111988,  0.50434204,  5.96394015],
       [ 7.41305296, 21.64302154,  1.07104461,  1.23839157,  0.33359878]])

Upvotes: 0

user2615660
user2615660

Reputation: 1

You have to call the resulting function:

return np.vectorize(scalar_function)(x, y)

This should do the work.

Upvotes: 0

memo
memo

Reputation: 177

based on this 'Please write a vector function vector_function, which will apply the operation 𝑓(𝑥,𝑦) defined above element-wisely with input vectors with same dimension x and y' here is what you are looking for:

import numpy as np
def scalar_function(x, y):
    if x <= y:
        return x*y
    else:
        return x/y

vector_function = np.vectorize(scalar_function, otypes = [float])

print(vector_function(np.array([1, 2, 3, 6]), np.array([1, 3, 4, 5])))
[Output]>>> [ 1.   6.  12.   1.2]

Upvotes: 1

Mikol-08
Mikol-08

Reputation: 1

Try this

vector_function = np.vectorize(scalar_function)

Upvotes: -1

Related Questions