6

I am using np.fromfunction to create an array of a specific sized based on a function. It looks like this:

import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(f, (len(test), len(test)), dtype=int)

However, I receive the following error:

TypeError: only integer arrays with one element can be converted to an index
sdasdadas
  • 23,917
  • 20
  • 63
  • 148
  • 1
    Just for reference: [Looking at numpy source](https://github.com/numpy/numpy/blob/v1.7.0/numpy/core/numeric.py#L1611) `fromfunction` just creates `indices` array and passes it to user function. So `i` and `j` are `array`s, not `int`s. – mg007 May 28 '13 at 20:15
  • @mg007 I believe the function will unbox those, however. – sdasdadas May 28 '13 at 20:20
  • You can see how it performs that task in this similar question: http://stackoverflow.com/questions/400739/what-does-mean-in-python – sdasdadas May 28 '13 at 20:23

1 Answers1

16

The function needs to handle numpy arrays. An easy way to get this working is:

import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(np.vectorize(f), (len(test), len(test)), dtype=int)

np.vectorize returns a vectorized version of f, which will handle the arrays correctly.

Florian Rhiem
  • 1,758
  • 1
  • 14
  • 23
  • 3
    passing the function through `np.vectorize` is _the_ trick documentation fails to point out, thank you so much – blue May 11 '16 at 14:05
  • 1
    Excellent trick! It ought to be in the docs. I had similar problem with trivial scenario `f = lambda i, j: 3.14` Running `np.fromfunction(f, (2, 6))` would simply give me a scalar 3.14 ! By contrast, `np.fromfunction(np.vectorize(f), (2, 6))` returns the expected 2x6 matrix whose entries are all 3.14 – Julian - BrainAnnex.org Jan 04 '19 at 04:44