Question: how to get dot products from size(x, n) matrix and length(n) vector

Matrix: X2, Vector: w2

What I’m trying to do is get the vector of dot products from each row of the matrix with the vector. The best I’ve come up with so far is:

sum(X2 .*  w2', dims=1)  

This works, but I have this nagging feeling that there’s a way to do it that makes it more obvious I’m doing dot products.

I benchmarked:

[dot(X2[i,:], w2) for i in 1:size(X2)[1]]

But, that’s an order of magnitude slower.

Could you clarify what output you are expecting? For

julia> X2 = reshape(1:6, 3, 2)
3×2 reshape(::UnitRange{Int64}, 3, 2) with eltype Int64:
 1  4
 2  5
 3  6

julia> w2 = [7, 8]
2-element Vector{Int64}:
 7
 8

your two proposed code snippets give:

julia> sum(X2 .*  w2', dims=1)
1×2 Matrix{Int64}:
 42  120

julia> [dot(X2[i,:], w2) for i in 1:size(X2)[1]]
3-element Vector{Int64}:
 39
 54
 69

The second looks more in line with your question (three rows and three elements in w2 yielding three dot products). If that’s indeed the output you’re after I’d suggest:

julia> X2 * w2
3-element Vector{Int64}:
 39
 54
 69
1 Like

shouldn’t

X2 * w2

julia> X2 = rand(1:3, 4, 3)
4×3 Matrix{Int64}:
 3  1  1
 1  2  3
 3  1  1
 2  3  3

julia> x2 = [1,2,3]
3-element Vector{Int64}:
 1
 2
 3

julia> X2 * x2
4-element Vector{Int64}:
  8
 14
  8
 17

just work?

3 Likes

You’re right. I’d been trying a bunch of different things in the repl, but I posted the wrong thing when I posted. It should have been:

sum(X2' .* w2, dims=1)

or

sum(X2 .* w2', dims=2)

But, I think the winner is X2 * w2. Stupid of me for not thinking of that, but thanks to you guys for looking at it and setting me on the right path!

1 Like