Van Peer
Van Peer

Reputation: 2167

adding scalar to an array in julia

Trying to get a linear equation y = m*x + c. I've the following lines of code, trying to add a scalar to an array.

m = 1.1; c = 0.11;
x = rand(1,2)
  1×2 Array{Float64,2}:
  0.920045  0.660015

y = m*x + c
ERROR: MethodError: no method matching +(::Array{Float64,2}, ::Float64)
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:502
  +(::Bool, ::T<:AbstractFloat) where T<:AbstractFloat at bool.jl:112
  +(::Float64, ::Float64) at float.jl:395
  ...
Stacktrace:
 [1] top-level scope at none:0

Currently using Julia 1.0. Directly adding a scalar to an array didn't work. In previous versions this used to work I suppose.

Scalar multiplication works

m*x
 1×2 Array{Float64,2}:
 1.01205  0.726016

But I've to define another array and then perform addition as shown.

c = [0.11 0.11]
y = m*x + c
1×2 Array{Float64,2}:
 1.12205  0.836016

Isn't this an overhead? What difference does it make when I can perform scalar multiplication m*x on arrays but not addition?

Upvotes: 10

Views: 10023

Answers (2)

Julia Learner
Julia Learner

Reputation: 2902

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

julia> m = 1.1
1.1
julia> c = 0.11
0.11
julia> 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 .+ c
1×2 Array{Float64,2}:
 0.964514  0.671738

# .+ operator is NOT used for the addition of the constant, get Error.    
julia> y = m*x + c
ERROR: 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.

Upvotes: 3

norok2
norok2

Reputation: 26886

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

Upvotes: 18

Related Questions