0

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)

and here is the output:

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)

and here is the output:

c
[[3 1]
 [5 5]]
f
[[0. 0.]
 [0. 0.]]

1 Answer 1

0

Since you're not modifying the array in place, you need to return it to the caller, and the caller can assign the returned value to a variable.

import numpy as np
def my_func(a,b):
    c=np.dot(a,b)
    print("c")
    return c
d = np.array([[1,2],[3,4]])
e = np.array([[-1,3],[2,-1]])
f = my_func(d,e)
print("f")
print(f)

Not the answer you're looking for? Browse other questions tagged or ask your own question.