Generalized matrix*vector operation

Hi everyone,

Take the following matrix and vector:

vij = [-2 -2 -2; 1 0 0; 0 1 0; 0 0 1; 1 1 1]
xj = [0.1 0.15 0.1]

This operation will work, resulting in a vector (as expected):

vij*xj'

However, if the matrix is reduced to one row and the vector to one element, as follows:

vij = [-2 -2 -2]
xj = [0.1]

; the previous calculation will fail.

The only line of code I have come up with to make it work in both cases is the following:

sum(vij.*xj, dims=2)

However, the trade-off is a higher computational cost, which may become relevant for large systems (> 1E6 rows/columns). I am trying to write a script that can be generalized to any matrix/vector system while being as efficient as possible.

Is there a way to make this sum(vij.*xj, dims=2) much faster, or just a different approach to this problem?

Why would you expect this to work? You can’t multiply a 1 \times 3 matrix by a 1-component vector in ordinary linear algebra.

You can multiply a 3 \times 1 matrix by a 1-component vector:

julia> matrix_3_1 = [1;2;3;;] # note the ;; to make this a 1-column matrix, not a vector
3×1 Matrix{Int64}:
 1
 2
 3

julia> x_1 = [4]
1-element Vector{Int64}:
 4

julia> matrix_3_1 * x_1
3-element Vector{Int64}:
  4
  8
 12

I’m confused about what operation you want to compute?

PS. Normally, you would write xj = [0.1, 0.15, 0.1] (note commas) in order to create a column vector in Julia. (As opposed to transposing [0.1 0.15 0.1], which creates a 3x1 matrix.)

4 Likes