Performing Operations on Vectors of Different Sizes Component-wise in Julia
Description
julia> x = [1 2 3]
1×3 Matrix{Int64}:
1 2 3
julia> y = [1 2 3 4]
1×4 Matrix{Int64}:
1 2 3 4
julia> x .+ y
ERROR: DimensionMismatch
Two vectors of different sizes cannot perform element-wise operations by default. To implement this manually, one would have to use a double for loop, but fortunately, it can be easily calculated by treating one as a row vector and the other as a column vector, returning a 2D array with element-wise operations. This is also possible in MATLAB or Python NumPy.
Despite differing sizes, it does not result in an error, caution is needed to ensure that it does not lead to unintended calculations.
julia> x' .+ y
3×4 Matrix{Int64}:
2 3 4 5
3 4 5 6
4 5 6 7
julia> x' .* y
3×4 Matrix{Int64}:
1 2 3 4
2 4 6 8
3 6 9 12
julia> x' ./ y
3×4 Matrix{Float64}:
1.0 0.5 0.333333 0.25
2.0 1.0 0.666667 0.5
3.0 1.5 1.0 0.75
It is also possible to use transpose(x)
instead of x'
.
Environment
- OS: Windows10
- Version: Julia 1.6.2