Dot product of multi-dimensional arrays

Hi guys,

I am trying to compute the dot product of matrices A & B but getting different results compared to when I use the numpy.dot(A, B).
A*B and A.*B also give different results.

According to numpy docs (numpy.dot — NumPy v1.23 Manual), this is what’s happening in my case: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]). How do I do this in Julia? Thanks!

Those are totally different operations in Julia. A * B is general matrix multiplication (or matrix-vector multiplication as appropriate). A .* B is the elementwise product of A and B (equivalent to what * does for numpy.ndarray).

Can you give a minimal example of the data you have, the result you want, and what you get instead?

1 Like

Welcome. I assume that you are new to Julia and I can’t easily check the numpy.dot function for some example result.
But perhaps you are just looking for:

julia> using LinearAlgebra

julia> a=rand(1:10,(3,3,3));

julia> b=rand(1:10,(3,3,3));

julia> dot(a,b)
973

Here’s an example
Julia

using LinearAlgebra
A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.; 0. 2. 0. 0. 0.]
F = svd(A)
u, s, v = F;
h = v'.*(diagm(s)*v)

Python

from scipy import linalg
import scipy as sp

A = sp.array(sp.mat('1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.; 0. 2. 0. 0. 0.'))
u, s, v = linalg.svd(A)
h = sp.dot(v.T, sp.dot(sp.diag(s), v))

Ok, thanks. You don’t want .* here at all–it’s not a “dot product” in the linear algebra sense, it’s an elementwise product.

Note also that the v you get from Julia is the adjoint of what you got in Python, but that’s easy to deal with. We can also use Diagonal to create a very cheap reference to s that behaves like a diagonal matrix, without actually filling in all the pointless zeros:

julia> h = v * Diagonal(s) * v'
5×5 Matrix{Float64}:
 0.447214  0.0      0.0  0.0  0.894427
 0.0       2.82843  0.0  0.0  0.0
 0.0       0.0      3.0  0.0  0.0
 0.0       0.0      0.0  0.0  0.0
 0.894427  0.0      0.0  0.0  1.78885
4 Likes

Ah, thanks!