2

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);
sparta93
  • 3,684
  • 5
  • 32
  • 63
  • 3
    Did you read the [documentation](http://www.mathworks.com/help/matlab/ref/arrayfun.html)? It's it just a `for` loop in disguise. You may even be able to vectorize the `sigmoid` function and get rid of the loop entirely. – horchler Mar 04 '15 at 00:56
  • 1
    @horchler it's not a for loop in disguise. It comes with its own optimizations. At the very least, if it doesn't optimize anything, it avoids the interpreter in each iteration. – carandraug Jun 08 '20 at 09:45

3 Answers3

4

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)
Oliver W.
  • 13,169
  • 3
  • 37
  • 50
  • 3
    And if your particular function is not directly vectorizable, and you're willing to take the performance hit in exchange for not doing any work, numpy provides numpy.vectorize(...) which is, effectively, the same for loop wrapping that the Matlab arrayfun(...) function is doing. – Ron Kaminsky Nov 20 '15 at 12:56
4

A generic way, use a loop:

 zj=[sigmoid(x) for x in aj]
Daniel
  • 36,610
  • 3
  • 36
  • 69
2

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.

Florian
  • 1,804
  • 2
  • 9
  • 19
  • To me, this is the better answer. arrayfun is a map operation of an arbitrary function iterated across all elements of an array. That's map in Python. – Alex Taylor Jan 08 '21 at 22:01