Numpy's fromfunction
method creates two arrays, one where the value at every cell is that cell's x index, and one where every cell is that cell's y index. It then applies the function you have passed in.
In your first call to the function, it does something like this:
x=[[0 0 0]
[1 1 1]
[2 2 2]]
y=[[0 1 2]
[0 1 2]
[0 1 2]]
result = fn(x,y)
where fn is your lambda function. Addition of numpy arrays is equivalent to element-wise addition, so this behaves how you would expect. However, in your second example, you are using max as your function, and the python builtin max function is not defined on numpy arrays. This is because the way the python max is defined is something like this:
def max(x,y):
if x>y:
return x
return y
However, x>y
is a numpy array if both x and y are numpy arrays, and if <numpy array>
doesn't make much sense, which is why we get the error message :
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In short, the function you are passing into numpy.fromfunction
is not being performed on each individual pair of numbers, but rather the matrices as a whole, generated as explained above. Numpy's method for computing element-wise maxima is numpy.maximum
, so replace max
with numpy.maximum
and your code will work as expected.
One last note: lambda x,y: max(x,y)
is equivalent to just max
, since both represent a function that takes two arguments and returns their max. so when you rewrite that line of your code, you can write:
B=numpy.fromfunction(numpy.maximum,(3,3),dtype=int)