-1

I have a matrix/numpy array A and need to carry out a function f to all elements and then store the result in a matrix B. How would I do this, I'm thinking of appending an empty array of B as I go on but is this the best way of doing it?

IVB_CODING
  • 23
  • 5
  • Does this answer your question? [Most efficient way to map function over numpy array](https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array) – NotAName Feb 21 '21 at 23:16
  • Tell us about `A` - shape and dtype. Also about `f`. What kind of input does it accept? – hpaulj Feb 22 '21 at 02:31
  • If the function only takes scalar values, it is hard to beat a list comprehension on a 1d list. If you've been told you should use `numpy` take some time to learn its basics. Poorly written `numpy` won't save you time. – hpaulj Feb 22 '21 at 03:56

2 Answers2

0

You can use numpy.vectorize:

A = np.arange(9).reshape((3,3))
#array([[0, 1, 2],
#       [3, 4, 5],
#       [6, 7, 8]])

my_func = lambda x: x + 1 #Example function
vect_func = np.vectorize(my_func)
B = vect_func(A)

Output

print(B)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Pablo C
  • 4,661
  • 2
  • 8
  • 24
0

Most operations can be done directly on the array itself. For example, if you want to add one to each element of the array, you would simply call;

arr2 = arr1+1

Vectorizing may be necessary if the required operation isn't universal, but will be at the expense of execution time. Vectorizing a function will still result in a looped operation, where as the universal functions (like above) are performed as scalars.

Boskosnitch
  • 774
  • 3
  • 8