Suppose I want to make a function that multiplies input vector by input matrix:
def MatMul(A,b):
return A.dot(b)
Now, I execute the following code:
import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]],dtype='float64')
b=np.array([4,5,6],dtype='float64')
c=np.zeros(3,dtype='float64')
c=MatMul(A,b)
Will there be additional array allocation inside MatMul function? I know that A and b will be passed by reference. Note, that I've already preallocated array c.
Generally, how to avoid unnecessary preallocations in simple functions like this? Say, I want to perform several mathematical operations:
def Rank1Update(A,b,alpha):
c=A.dot(b)
c+=alpha*c.dot(c)*c
return c
I can fit many mathematical functions in 1 line, but code quickly becomes unreadable.
I am familiar with C-style programming, where in order to avoid unnecessary memory allocations one would pass A,b and c by references and update c inside the functions that returns void. I can do the same in python, but I want to use return for my convenience and code readability,
Thanks,
Mikhail
Numpy, in most of its functions that produce new arrays, has a parameter to store the resulting array. I used the names version of that parameter, out, in my code below, but you can leave out the name. You must make sure that the out array has the correct shape and dtype. The purpose of this parameter is exactly what you want--to avoid additional memory allocation. This can also speed up the code.
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype='float64')
b = np.array([4, 5, 6], dtype='float64')
c = np.zeros(3, dtype='float64')
A.dot(b, out=c)
That parameter is mentioned in the documentation for dot(). If you want to change the definition of function MatMul,
def MatMul(A, b, c=None):
return A.dot(b, out=c)
and change the call to
MatMul(A, b, c)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With