I have made a matrix multiplier with recursion. Problem is that the return value only remembers the first iteration. The function works. It actually produces correct matrix multiplication for more than 2 matrices. I can probably fix this if I use a global variable but I want to know if there is another way to do this.
def m_multiple(*args):
storage = [matrix for matrix in args]
for no_matrix in range(0, len(storage)): # Number of matrix
result = [[0 for _ in range(len(storage[no_matrix 1][0]))] for _ in range(len(storage[no_matrix]))]
for row in range(len(storage[no_matrix])): # row of first matrix
for column in range(len(storage[no_matrix 1][0])): # column of second matrix
for row2 in range(len(storage[no_matrix 1])): # row of second matrix
result[row][column] = storage[no_matrix][row][row2] * storage[no_matrix 1][row2][column]
break
if len(storage) > 2:
storage.pop(0)
storage.pop(0)
storage.insert(0, result)
m_multiple(*storage)
return result
For example:
def main():
x = [[2, 2], [2, 2]]
y = [[3], [2]]
z = [[1, 2]]
a = [[1], [1]]
print(m_multiple(x, y, z, a))
if __name__ == '__main__':
main()
# Answer: (With print values at every stage of the recursion in m_multiple())
# [[10], [10]]
# [[10, 20], [10, 20]]
# [[30], [30]]
# [[10], [10]] <- Actual return output
CodePudding user response:
A minute change on your code will make the program work fine
Solution:
You should return the value returned by recursive call, instead you were just performing the function.
This line has been changed:
return m_multiple(*storage)
Here is the code:
def m_multiple(*args):
storage = [matrix for matrix in args]
for no_matrix in range(0, len(storage)): # Number of matrix
result = [
[0 for _ in range(len(storage[no_matrix 1][0]))]
for _ in range(len(storage[no_matrix]))
]
for row in range(len(storage[no_matrix])): # row of first matrix
for column in range(
len(storage[no_matrix 1][0])
): # column of second matrix
for row2 in range(len(storage[no_matrix 1])): # row of second matrix
result[row][column] = (
storage[no_matrix][row][row2]
* storage[no_matrix 1][row2][column]
)
break
if len(storage) > 2:
storage.pop(0)
storage.pop(0)
storage.insert(0, result)
return m_multiple(*storage)
return result
def main():
x = [[2, 2], [2, 2]]
y = [[3], [2]]
z = [[1, 2]]
a = [[1], [1]]
print(m_multiple(x, y, z, a))
if __name__ == "__main__":
main()
Output:
[[30], [30]]