How to change numpy arrays in a function and return the values?

I’m writing code which does matrix operations in functions and I’m using numpy arrays to store my matrices. From reading books/ discussions on here I have got as far as understanding that scalar arguments of functions are passed by value and arrays are passed in C-like style (in C we would say a pointer to the array is being passed and an equivalent thing is happening in Python).

Here are two simple Python codes, the first successfully multiplies 2 matrices together and passes the matrix back to the calling code. I achieved this by hand-coding the matrix multiplication following a hint I saw on here (or a similar forum). In the 2nd I replace the hand-coded matrix multiplication by c=np.dot(a,b) and the matrix product doesn’t get passed back.

How do I get the 2nd approach to work?

Example 1:
import numpy as np
def my_func(a,b,c):
for i in range (0,2):
for j in range (0,2):
c[i,j]=0.
for k in range(0,2):
c[i,j]=c[i,j]+a[i,k]*b[k,j]
print(“c”)
print(c)
d = np.array([[1,2],[3,4]])
e = np.array([[-1,3],[2,-1]])
f = np.zeros((2,2))
my_func(d,e,f)
print(“f”)
print(f)
Output from example 1:
c
[[3. 1.]
[5. 5.]]
f
[[3. 1.]
[5. 5.]]

Example 2:
import numpy as np
def my_func(a,b,c):
c=np.dot(a,b)
print(“c”)
print(c)
d = np.array([[1,2],[3,4]])
e = np.array([[-1,3],[2,-1]])
f = np.zeros((2,2))
my_func(d,e,f)
print(“f”)
print(f)
Output from example 2:
c
[[3 1]
[5 5]]
f
[[0. 0.]
[0. 0.]]

In the second case, the assignment c=np.dot(a,b) rebinds the local variable c to reference a different array. It doesn’t modify the original array, which is why the array referenced by f is unchanged after the function returns.

To modify the array referenced by c, you need to assign to some index instead of to the name c itself. For example, using a broadcasted assignment:

c[:, :] = np.dot(a, b)

or using NumPy’s ... shorthand:

c[...] = np.dot(a, b)

You can also use the matrix multiplication operator @ in place of np.dot:

c[...] = a @ b

For more on how assignments work in Python, I usually recommend Facts and myths about Python names and values | Ned Batchelder. You may also find these SO questions helpful:

In future posts, you can format code as formatted text by surrounding it with triple-backticks (```).