adding scalar to an array in julia adding scalar to an array in julia arrays arrays

adding scalar to an array in julia


I guess this has become stricter.In Julia syntax (like in MATLAB), + and * operate on congruent arrays.

For element-wise operation, you should use .+ and .*.Strangely, this does not seem to matter for * but it does for +.

Anyway, both the following works:

y = m * x .+ c

and:

y = m .* x .+ c


This code illustrates Bogumił Kamiński's helpful comment:

julia> m = 1.11.1julia> c = 0.110.11julia> x = rand(1,2)1×2 Array{Float64,2}: 0.77683  0.510671# .+ operator IS used for the addition of the constant.    julia> y = m*x .+ c1×2 Array{Float64,2}: 0.964514  0.671738# .+ operator is NOT used for the addition of the constant, get Error.    julia> y = m*x + cERROR: MethodError: no method matching +(::Array{Float64,2}, ::Float64)

You are not alone in wanting to do a matrix + a scalar operation, see here.

However, whether it is allowed depends on how you define your math and how you define your software. I have written data matrix software where adding a scalar to a matrix is a standard operation.

However, the rules for that software were quite different from the rules for matrices in standard linear algebra. For example, in the data matrix algebra employed by that software, AB = BA, thus commutative for matrix multiplication because the matrix multiplication operator was defined as element-by-element multiplication.

That is totally different from standard matrix algebra, but was what I wanted.