# Generalized matrix\*vector operation

**URL:** https://discourse.julialang.org/t/generalized-matrix-vector-operation/103683
**Category:** Numerics
**Tags:** linearalgebra
**Created:** [September 8, 2023, 10:32pm UTC](https://discourse.julialang.org/t/generalized-matrix-vector-operation/103683 "2023-09-08T22:32:38Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![SantiagoOrtiz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/santiagoortiz/32/25378_2.png) [@SantiagoOrtiz](https://discourse.julialang.org/u/SantiagoOrtiz)
#### Post date: [September 8, 2023, 10:32pm UTC](https://discourse.julialang.org/t/generalized-matrix-vector-operation/103683/1 "2023-09-08T22:32:38Z")

</div>

Hi everyone,

Take the following matrix and vector:

```julia
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):

```julia
vij*xj'

```

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

```julia
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:

```julia
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?

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [September 9, 2023, 1:32am UTC](https://discourse.julialang.org/t/generalized-matrix-vector-operation/103683/2 "2023-09-09T01:32:10Z")

</div>

> [@SantiagoOrtiz](#):
>
> However, if the matrix is reduced to one row and the vector to one element, as follows:
> 
> ```julia
> vij = [-2 -2 -2]
> xj = [0.1]
> 
> ```

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
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.)
