-1

The numpy.fromfunction makes a single call to the function with arguments as arrays, as described in e.g. this answer. So to use numpy.fromfunction it is required that the function takes array arguments and return an array also.

How to make numpy array based on function called for each element, where the function returns a scalar for the element, as for example using the max function like below ?

z = numpy.fromfunction(max, (2, 2), dtype=int)

Which would then return:

[[0 1]
 [1 1]]
Community
  • 1
  • 1
EquipDev
  • 5,573
  • 10
  • 37
  • 63
  • Not sure I get your question: z will be scalar so why should it be an array? – Roelant Apr 10 '17 at 11:29
  • 2
    Why don't you just use `np.max` or if you want to use another function what is that exactly? Is there no equivalent for that in numpy? – Mazdak Apr 10 '17 at 11:35
  • @Kasramvd: Max was just an example function; the question is still thought to be a matter for a general solution. – EquipDev Apr 10 '17 at 11:42

1 Answers1

2

You can use numpy.vectorize for that

vmax = numpy.vectorize(max)
z = numpy.fromfunction(vmax, (2, 2), dtype=int)

Please note this sentence from the docs though:

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

By its very nature numpy.vectorize will be slow. In this example numpy.maximum will be much faster:

z = numpy.fromfunction(numpy.maximum, (2, 2), dtype=int)
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • For a general solution that is fine. My engineering performance will be higher when writing like that, and if the code then executes too slowly I will optimize later :-) – EquipDev Apr 10 '17 at 11:45
  • 1
    I understand. I am just arguing that you should try and use `numpy` functions wherever possible. – Nils Werner Apr 10 '17 at 12:05