Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrayfun in Python?

Tags:

python

matlab

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);
like image 733
sparta93 Avatar asked Sep 22 '26 01:09

sparta93


2 Answers

A generic way, use a loop:

 zj=[sigmoid(x) for x in aj]
like image 164
Daniel Avatar answered Sep 23 '26 16:09

Daniel


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)
like image 26
Oliver W. Avatar answered Sep 23 '26 14:09

Oliver W.