If you have numpy arrays you can use the np.dot function for this:

np.dot(A, B)

It will do exactly what you want, i.e. "contract" the last axis of A with the first axis of B:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:

 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
Answer from filmor on Stack Overflow
Top answer
1 of 2
5

If you have numpy arrays you can use the np.dot function for this:

np.dot(A, B)

It will do exactly what you want, i.e. "contract" the last axis of A with the first axis of B:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:

 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
2 of 2
0

First of all any multidimensional array is a n times b split of a flatten array. The 2,3,2 dimension array, [ [ [A,B],[C,D],[E,F] ], [ [G,H],[I,J],[K,L] ] ] is simply divide A,B,C,D,E,F,G,H,I,J,K,L into 2 pieces , then 3 pieces, then 2 pieces again and there is your multidimensional array. Vectors are here two dimensional.

Secondly, two dimensional matrix multiplication is also fixed length vector multiplication with a combination. (n,m)*(m,l) dimensional matrix multiplication is actually term by term multiplication and sum of results of l different m vectors and n different m vectors. l times n combination of two different m vectors.

When you get that you simply can convert 20 dimension matrix to two dimension matrix with same vector size and multiply them and reshape it back.

Quick Example:

import numpy as np

a=np.random.random(120).reshape(2,5,3,4)
b=np.random.random(120).reshape(5,3,4,2)

br=np.rollaxis(b,3,2).reshape(30,4).T  
# converted all combinations to a series of 4 dimension vectors here 

test1=np.matmul(a.reshape(30,4),br).reshape(2,5,3,5,3,2)
test2=np.dot(a,b)

np.all(test1==test2)

returns

array(True)

lets do it basically for all combinations (dimensions)

sa=a.shape
sb=b.shape
res=np.ndarray([sa[0],sa[1],sb[0],sb[1],sa[2],sb[3]])
for i in range(a.shape[0]):
  for j in range(a.shape[1]):
    for k in range(b.shape[0]):
      for n in range(b.shape[1]):
        x=np.matmul(a[i,j],b[k,n])
        np.append(res,x)
print(np.any(res==np.dot(a,b).reshape(2,5,5,3,3,2)))

returns

True

USE CASE:

Suppose we have a case such as for 10 different materials and 20 different geometries 3 different physical quantity in 3 dimensions vectors will be matrix multiplied for a geometry and physics processing neural network layer which will be calculated with genetic selective algorithm which has neural connection coefficient vectors of 5 different groups of population each having 100 different gene sequence (population) and 20 neural nodes. In a such case you may benefit calculating it at once or you can somehow serialize this calculation to two flat arrays and send it to your gpu or cpu according to your concurrent free ram amount. In such case you may want to understand how this calculations work.

In any case of multidimensional matrix calculation combinations of vectors are calculated term by term You may want to multiply first term with seconds vectors last term and sum the rest. It is up to you but understanding how it works is important. So here is a simple illustration I have used to undestand this.

[ [ [A,B],[C,D],[E,F] ], [ [G,H],[I,J],[K,L] ] ] --> ABCDEFGHIJKL [ [ [1,2],[3,4],[5,6] ], [ [7,8],[9,0],[€,$] ] ] --> 1234567890€$

use operator(multiply) term by term shifting first array by amount of vector size (2)

ABCDEFGHIJKL   CDEFGHIJKLAB  FGHIJKLABCDE ...
1234567890€$   1234567890€$  1234567890€$ ...

Here comes all combinations

append all of them and reshape and use another operator (+)

[A+2*B],[C*3+D*4],[E*5,F*6] ...... [I*€+J*$] 

Hope this helps and saves time to grasp this.

🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-3d-matrix-multiplication
NumPy - 3D matrix multiplication - GeeksforGeeks
July 23, 2025 - A 3D matrix is nothing but a collection ... So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors....
Discussions

python - Pythonic multidimensional matrix multiplication - Stack Overflow
Matrix of floats A and B have dimensions (1000,120) and (1000,120,3). I want to multiply them so that the resulting matrix M should have dimensions (1000,120,3) and the logic should be that it M[0... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I do multidimensional matrix multiplication in numpy, scipy - Stack Overflow
I have a scipy sparse matrix with shape (8,9) and another array with shape (9, 12 , 17). I want to multiply these such that I get a matrix/array of size (8,12,17) where the (8,9) matrix has effecti... More on stackoverflow.com
🌐 stackoverflow.com
July 29, 2016
python - Multidimensional matrix multiplication on numpy array - Stack Overflow
I'm implementing a neural network in python, as a part of backpropagation I need to multiply a 3D matrix,call it A, dimension (200, 100, 1) , by a 2D matrix, call it W,dimension (100, 200) the result More on stackoverflow.com
🌐 stackoverflow.com
February 11, 2017
numpy - Multiple dimension matrix multiplication in Python - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
April 30, 2017
🌐
TutorialsPoint
tutorialspoint.com › article › python-program-to-multiply-to-matrix-using-multi-dimensional-arrays
Python Program to Multiply to Matrix Using Multi-dimensional Arrays
March 27, 2026 - We can implement standard matrix multiplication using nested loops to iterate through rows and columns ? # Define matrices using multidimensional arrays matrix_a = [[1, 2, 3], [4, 1, 2], [2, 3, 1]] matrix_b = [[1, 2, 3, 2], [2, 3, 6, 3], [3, 1, 4, 2]] def display(matrix): for row in matrix: print(row) print() # Display input matrices print('The first matrix is:') display(matrix_a) print('The second matrix is:') display(matrix_b) # Initialize result matrix with zeros result = [[0 for j in range(len(matrix_b[0]))] for i in range(len(matrix_a))] # Multiply matrices using nested loops for i in range(len(matrix_a)): for j in range(len(matrix_b[0])): for k in range(len(matrix_b)): result[i][j] += matrix_a[i][k] * matrix_b[k][j] print('The multiplication result is:') display(result)
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.matmul.html
numpy.matmul — NumPy v2.5 Manual
Vector-matrix product for stacks of vectors and matrices. ... Sum products over arbitrary axes. ... Einstein summation convention. ... The behavior depends on the arguments in the following way. If both arguments are 2-D they are multiplied like conventional matrices.
🌐
Stack Overflow
stackoverflow.com › questions › 56277781 › pythonic-multidimensional-matrix-multiplication
python - Pythonic multidimensional matrix multiplication - Stack Overflow
Matrix of floats A and B have dimensions (1000,120) and (1000,120,3). I want to multiply them so that the resulting matrix M should have dimensions (1000,120,3) and the logic should be that it M[0...
Find elsewhere
🌐
Hackr
hackr.io › home › articles › data, analysis, & ai
Numpy Matrix Multiplication - NumPy v1.17 Manual [Updated]
January 30, 2025 - You can also download Anaconda Python distribution as it is much easier for starters. Download it from here. For multiplying two matrices, use the dot () method. Here is an introduction to numpy.dot( a, b, out=None) ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › numpy-matrix-multiplication
NumPy Matrix Multiplication: Methods and Examples | DigitalOcean
August 4, 2022 - Perform matrix multiplication in NumPy using dot(), matmul(), and @ operator. Complete guide with examples for 2D, 3D arrays and performance tips.
🌐
Reddit
reddit.com › r/learnpython › how to multiply matrices with different dimensions
r/learnpython on Reddit: How to multiply matrices with different dimensions
December 5, 2021 -

I'm trying to multiply A = 20x1x10 with B = 10x20 and I'm supposed to get a 20x1x20 matrix as the output. So far I've tried

C = numpy.matmul(A,B)
# and 
C = A @ B

But all of them seem to result a 20x20x20 matrix. Any idea how to proceed from here?

For better context, A = jacobian output of derivative of an activation function in a neural network, with shape of (N samples * 1 * values) and B = changes in output of the layer

🌐
Board Infinity
boardinfinity.com › blog › how-to-perform-matrix-multiplication-with-numpy-python
How to perform Matrix Multiplication with Numpy Python
July 11, 2023 - In order to determine the matrix product of two arrays, use the np.matmul() function. The NumPy arrays' matrix multiplication is returned by the matmul() method, which accepts the inputs board_arr1 and board_arr2.
🌐
DataCamp
datacamp.com › doc › numpy › matrix-multiplication
NumPy Matrix Multiplication
Matrix multiplication in NumPy is used when you need to perform dot product operations between two matrices or a matrix and a vector. The numpy.matmul() or the @ operator can be used for this purpose.
🌐
Vultr Docs
docs.vultr.com › python › third party › numpy › multiply()
Python Numpy multiply() - Multiply Array Elements | Vultr Docs
November 18, 2024 - Define a multidimensional array. Apply numpy.multiply() with a scalar to the array. ... import numpy as np matrix = np.array([[1, 2], [3, 4]]) result = np.multiply(matrix, 3) print(result)
🌐
Educative
educative.io › blog › numpy-matrix-multiplication
NumPy matrix multiplication: Get started in 5 minutes
April 30, 2026 - It also breaks down our tasks into multiple pieces and processes each piece concurrently. Before we get started, let’s make sure we have NumPy installed. If you already have Python, you can install NumPy with one of the following commands: ... If you’re looking to learn Python data structures, start off with this helpful Python tutorial! A matrix is a 2-D array.
🌐
Educative
educative.io › answers › how-to-multiply-matrices-in-numpy
How to multiply matrices in NumPy
For example, if matrix 1 has dimensions a * N and matrix 2 has dimensions N * b, then the resulting matrix has dimensions of a * b. ... To multiply two matrices use the dot() function of NumPy.
🌐
Wordpress
jameshensman.wordpress.com › 2010 › 06 › 14 › multiple-matrix-multiplication-in-numpy
Multiple Matrix Multiplication in numpy | James Hensman's Weblog
June 14, 2010 - There are two ways to deal with matrices in numpy. The standard numpy array in it 2D form can do all kinds of matrixy stuff, like dot products, transposes, inverses, or factorisations, though the s…