7

Lets say I create a 3x3 NumPy Matrix. What is the best way to apply a function to all elements in the matrix, with out looping through each element if possible?

import numpy as np    

def myFunction(x):
return (x * 2) + 3

myMatrix = np.matlib.zeros((4, 4))

# What is the best way to apply myFunction to each element in myMatrix?

EDIT: The current solutions proposed work great if the function is matrix-friendly, but what if it's a function like this that deals with scalars only?

def randomize():
    x = random.randrange(0, 10)
    if x < 5:
        x = -1
    return x

Would the only way be to loop through the matrix and apply the function to each scalar inside the matrix? I'm not looking for a specific solution (like how to randomize the matrix), but rather a general solution to apply a function over the matrix. Hope this helps!

Branson Camp
  • 641
  • 1
  • 9
  • 18
  • 2
    For many basic functions, operators and expressions from them it is just `myFunction(myMatrix)` – Michael Butscher Nov 18 '18 at 03:33
  • 2
    Your function works with the whole array. But if the function really only worked with scalars, some sort of python loop is required. – hpaulj Nov 18 '18 at 03:48

1 Answers1

-3

This shows two possible ways of doing maths on a whole Numpy array without using an explicit loop:

import numpy as np                                                                          

# Make a simple array with unique elements
m = np.arange(12).reshape((4,3))                                                            

# Looks like:
# array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 9, 10, 11]])

# Apply formula to all elements without loop
m = m*2 + 3

# Looks like:
# array([[ 3,  5,  7],
#       [ 9, 11, 13],
#       [15, 17, 19],
#       [21, 23, 25]])

# Define a function
def f(x): 
   return (x*2) + 3 

# Apply function to all elements
f(m)

# Looks like:
# array([[ 9, 13, 17],
#       [21, 25, 29],
#       [33, 37, 41],
#       [45, 49, 53]])
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • 1
    Passing array to function doesn't make the function called on each element, as the questions asking about, it does call function with the array. – Sergey Kostrukov Sep 30 '21 at 04:52