Apply a function to each element of a python matrix

Asked

Viewed 526 times

0

I need to apply a lambda function to all elements of a matrix in and it returns a matrix of the same size type like this:

i have the matrix mat in numpy style:

mat = array[[1, 2, 3],
            [4, 5, 6]]

and the following lambda function:

soma3 = lambda x: x + 3

then I apply this function to the matrix and it returns the following matrix:

array[[4, 5, 6],
      [7, 8, 9]]

thanks in advance for the help

2 answers

2


There are several ways to do this you want, using Numpy, you can make use of the vectorize:

import numpy as np

mat = np.array([[1, 2, 3],[4, 5, 6]])

soma3 = lambda x: x + 3

vectorize = np.vectorize(soma3)

print(vectorize(mat))

https://numpy.org/doc/1.17/reference/generated/numpy.vectorize.html


There are other ways to do this without using Numpy, such as creating a lambda make a for on your list:

mat = [[1, 2, 3],[4, 5, 6]]

soma3 = lambda x: [y + 3 for y in x]

mat = list(map(soma3, mat))

print(mat)

You can also create a lambda inside of another:

mat = [[1, 2, 3],[4, 5, 6]]

soma3 = lambda x: list(map(lambda y: y + 3, x))

mat = list(map(soma3, mat))

print(mat)

And finally, you can even create a lambda to call a function from you:

def somar3(lista):
  for index, item in enumerate(lista):
    lista[index] = item + 3

  return lista

mat = [[1, 2, 3],[4, 5, 6]]

soma3 = lambda x: somar3(x)

mat = list(map(soma3, mat))

print(mat)
  • 2

    In the last example, I find it "exaggerate" to use a lambda that only calls the function, can pass the direct function: mat = list(map(somar3, mat)) :-)

1

If you just want to apply mathematical operations to all elements of your array it is much easier for you to simply add the number you want to your array:

import numpy as np

array = np.array([[1, 2, 3],
                  [4, 5, 6]])

print(array + 3)
# [[4 5 6]
#  [7 8 9]]

See working on Repl.it

You can check in session "Quickstart tutorials" of numpy documentation where it says:

Arithmetic Operators on arrays apply elementwise. A new array is created and filled with the result.

Free translation:

Arithmetic operators are applied to each array element. A new array is created and filled with the result.

If you need some more complex operation in your array maybe vectorize be better for your case, but remember that in your documentation there’s a note where it says:

The vectorize Function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

Free translation:

The function vectorize is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.