4

im trying to use fromfunction to create a 5x5 matrix with gaussian values of mu=3 and sig=2, this is my attempt :

from random import gauss
import numpy as np
np.fromfunction(lambda i,j: gauss(3,2), (5, 5))

this is the result : 5.365244570434782

as i understand from the docs this should have worked, but i am getting a scalar instead of 5x5 matrix... why? and how to fix this?

Ofek Ron
  • 8,354
  • 13
  • 55
  • 103

2 Answers2

13

The numpy.fromfunction docs are extremely misleading. Instead of calling your function repeatedly and building an array from the results, fromfunction actually only makes one call to the function you pass it. In that one call, it passes a number of index arrays to your function, instead of individual indices.

Stripping out the docstring, the implementation is as follows:

def fromfunction(function, shape, **kwargs):
    dtype = kwargs.pop('dtype', float)
    args = indices(shape, dtype=dtype)
    return function(*args,**kwargs)

That means unless your function broadcasts, numpy.fromfunction doesn't do anything like what the docs say it does.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • So how would you use fromfunction in my use case? – Ofek Ron Nov 18 '16 at 08:32
  • @OfekRon I don't know. However, I believe `numpy` has a `random` module that should already provide the ability to create arrays with elements from gaussian distributions etc... – Bakuriu Nov 18 '16 at 08:33
  • @Bakuriu can you be more specific? – Ofek Ron Nov 18 '16 at 08:34
  • 2
    @OfekRon: I wouldn't. I'd use [`numpy.random.normal`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html) instead of `random.gauss`. – user2357112 Nov 18 '16 at 08:34
  • 1
    @user2357112 np.random.normal(3,2,(5,5)) works great!, wonder why gauss function exists but oh well – Ofek Ron Nov 18 '16 at 08:38
  • 2
    @OfekRon That would be because python's `random` module is different from numpy's `random` module. – jadsq Nov 18 '16 at 08:42
2

I know this is an old post, but for anyone stumbling upon this, the reason why it didn't work is, the expression inside lambda is not making use of the i, j variables

what you need could you achieved like this:

np.zeros((5, 5)) + gauss(3, 2)
nshathish
  • 417
  • 8
  • 23