Lambda functions in numpy from function array constructor

What happened to the last line of the following code creating matrix B?

Why is the use of the max function different from the simple expression i + j in the previous line?

import numpy
print('Version =', numpy.version.version) # = 1.11.1
A=numpy.fromfunction(lambda i,j: i+j, (3,3), dtype=int)
B=numpy.fromfunction(lambda i,j: max(i,j),(3,3),dtype=int)
+4
source share
1 answer

The Numpy method fromfunctioncreates two arrays: one where the value in each cell is the index of cell x and where each cell is the index of cell y. Then it applies the function in which you passed.

When the function is first called, 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)

fn - -. numpy , , . , max , max max python numpy. , python max :

def max(x,y):
    if x>y:
        return x
    return y

x>y numpy, x y numpy, if <numpy array> , :

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

, , numpy.fromfunction, , , , . Numpy numpy.maximum, max numpy.maximum, , .

: lambda x,y: max(x,y) max, , max. , , :

B=numpy.fromfunction(numpy.maximum,(3,3),dtype=int)
+3

Source: https://habr.com/ru/post/1661301/


All Articles