In MATLAB, I can do the following operation:
[1 2 3; 4 5 6] + [-1 -2 -3]
This will return [0 0 0; 3 3 3], as it understands that I want to perform the addition of the vector with each row of the matrix.
How can I do this in Julia? If I try, it gives me this error:
ERROR: DimensionMismatch("dimensions must match: a has dims (Base.OneTo(2), Base.OneTo(3)), b has dims (Base.OneTo(1), Base.OneTo(3)), mismatch at 1")
>Solution :
Add a dot in front of + like this:
julia> [1 2 3; 4 5 6] .+ [-1 -2 -3]
2×3 Matrix{Int64}:
0 0 0
3 3 3
However, note that [-1 -2 -3] is not a vector in Julia. It is a matrix having one row:
julia> [-1 -2 -3]
1×3 Matrix{Int64}:
-1 -2 -3
In Julia a vector would be [1, 2, 3] and vectors are always treated as columnar:
julia> [1, 2, 3]
3-element Vector{Int64}:
1
2
3
The reason why:
[1 2 3; 4 5 6] + [-1 -2 -3]
fails is that it is an incorrect expression from a mathematical perspective. These two matrices: [1 2 3; 4 5 6] and [-1 -2 -3] are representing linear operators having different spaces they operate on and adding such linear operators is typically considered as not allowed in mathematics.
However, if matrices had the same shape you could add them as linear operators then have the same dimension of the from and to spaces so they can be added:
julia> [1 2; 3 4] + [5 6; 7 8]
2×2 Matrix{Int64}:
6 8
10 12
(such an operation is mathematically well defined)
You can read more about broadcasting here.