Skip to content Skip to sidebar Skip to footer

Arrayfun In Python?

I'm trying to convert some code from Matlab to Python. Any idea how I would go about converting this line? I'm very new to python and I've never seen arrayfun before. Thanks. Much

Solution 1:

You will want to use the numerical library numpy whenever you're working with numerical data.

In it, the Matlab function called arrayfun is simply the vectorized form of that function. E.g.

Matlab:

>> a = 1:4

a =

     1234>> arrayfun(@sqrt, a)

ans =

    1.00001.41421.73212.0000>> sqrt(a)

ans =

    1.00001.41421.73212.0000

Whereas in numpy, you'd do:

>>>import numpy as np>>>a = np.arange(4)>>>np.sqrt(a)
array([ 0.        ,  1.        ,  1.41421356,  1.73205081])

Most functions can be vectorized, a sigmoid is no exception to that. For example, if the sigmoid were defined as 1./(1 + exp(-x)), then you could write in Python:

defsigmoid(x):
    return1./(1 + np.exp(-x))

zj = sigmoid(aj)

Solution 2:

A generic way, use a loop:

zj=[sigmoid(x) for x in aj]

Solution 3:

Though all the replies are correct and the list comprehension is probably the preferred way of writing it as it reads so elegantly, I do feel compelled to make one addition: the most direct translation of arrayfun to Python in my opinion is still map. It returns an iterator, which can e.g. be passed to list do mimic exactly what arrayfun would do for you. In other words, list(map(sigmoid,aj)) would be a more direct translation of arryfun(@sigmoid,aj) in my opinion.

Post a Comment for "Arrayfun In Python?"