Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Broadcasting vector to matrix to calculate sum (MATLAB style)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading