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 appreciated.
zj=arrayfun(@sigmoid,aj);
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 appreciated.
zj=arrayfun(@sigmoid,aj);
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 =
1 2 3 4
>> arrayfun(@sqrt, a)
ans =
1.0000 1.4142 1.7321 2.0000
>> sqrt(a)
ans =
1.0000 1.4142 1.7321 2.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:
def sigmoid(x):
return 1./(1 + np.exp(-x))
zj = sigmoid(aj)
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.