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.

Here is a gdscript function to do matrix multiplication: Sorry forgot to add the zero_matrix function. That just creates a matrix full of zeros to work with. The zero_matrix function just creates a matrix full of zeros to work with.

zero_matrix: nX = number of rows nY = number of columns

multiply: a = matrix 1 b = matrix 2

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

Thanks for the reply. It seems looks like there is no function which can be called to create a matrix of a given size from the link > @ron said:

Here is a gdscript function to do matrix multiplication: Sorry forgot to add the zero_matrix function. That just creates a matrix full of zeros to work with. The zero_matrix function just creates a matrix full of zeros to work with.

zero_matrix: nX = number of rows nY = number of columns

multiply: a = matrix 1 b = matrix 2

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

Thank a lot for your reply. Do you happen to know if there are matrix functions which come out-of-the-box, rather than having to manually code all the required matrix related functions (e.g. like Vector2, Vector3, .dot(), but for matrices rather than vectors)?

Not as far as I know. I have to creat my own linear algebra code to do what I want. Sorry

4 years later