Matrix-Matrix/Vector multiplication

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MangoTree

Hi all,

How would one carry out a matrix-matrix multiplication (and matrix-vector multiplication)? For example, if I want to multiply two 2x2 matrices together:

[[1,2], [3,4]] and [[5,6],[7,8]]

Is there a GDScript function which can be called on these arrays to perform a matrix multiplication (and btw [[1,2], [3,4]] * [[5,6],[7,8]] doesn’t work)?
The way of achieving this in numpy would be using @ , i.e.:

[[1,2], [3,4]]@[[5,6],[7,8]] (gives [[19,22],[43,50]])

Is there an equivalent operator in GDScript?

Thanks in advance.

:bust_in_silhouette: Reply From: Player0330

Hey, use this code. Add this function and do multiply(array1, array2).
Crediits to https://godotforums.org/discussion/20590/matrix-matrix-vector-multiplication

func zero_matrix(nX, nY):
  var matrix = []
  for x in range(nX):
      matrix.append([])
      for y in range(nY):
          matrix[x].append(0)
  return matrix
func multiply(a, b):
  var matrix = zero_matrix(a.size(), b[0].size())
  
  for i in range(a.size()):
      for j in range(b[0].size()):
          for k in range(a[0].size()):
              matrix[i][j] = matrix[i][j] + a[i][k] * b[k][j]
  return matrix

That’s an answer to the exact same person just on a different page XD

BlockOG | 2020-12-04 16:22