问题描述:

This question already has an answer here:

Parameters to numpy's fromfunction

4 answers

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)
```

您可能感兴趣的文章：

- html - Use ellipsis until min-width, then wrap to next line
- Swift Vapor unsupported_grant_type invalid signature / OAuth access token
- html - Rotate SVG Element Around Position Specified in Percentage
- sandbox - Not able to upload Photos gallery video but able upload videos shoot from camera iOS
- html - CSS will not read class names contained in quotes
- php - Reading a specific line from a text file
- clr - Any implementation of an Unrolled Linked List in C#?
- Finding Hudson Log Files
- Forward to a payment-gateway together with POST data using cURL (or any other PHP server side solution)
- WCF in Winforms app - is it always single-threaded?

随机阅读：

**推荐内容**-

**热点内容**