Mutation of a scalar variable

Hi,

I’d like to mutate a scalar variable.
For example, if x is a vector, then

x .= x_new

works fine for mutation.
However, when x is a Number, e.g., x = 1.0,

x .= x_new

does not work properly.
Also, I cannot find a way to mutate a scalar variable x.

1.0 is a Float64 which is immutable, it cannot be mutated. You should instead just rebind it

x = x_new

Why did you want to mutate a number?

1 Like

For some reason, my code is well-defined with mutation of arrays.
However, when I’m trying to deal with the case of an array whose length is 1,
it is quite uncomfortable (for example, I have to use x .* x or x[1] * x[1] instead of x * x).
So I wonder if there is a way of mutating scalar variable.

You cannot mutate scalar values.

But a 1x1 array is not a scalar, and you can mutate it just fine. Also, you can do x*x:

jl> x = rand(1,1)
1×1 Matrix{Float64}:
 0.040743095726171186

jl> x * x
1×1 Matrix{Float64}:
 0.0016599998493519487

It doesn’t work for vectors, though, since multiplication isn’t defined for vectors:

jl> x = rand(1)
1-element Vector{Float64}:
 0.5736316758843656

jl> x * x
ERROR: MethodError: no method matching *(::Vector{Float64}, ::Vector{Float64})

In what way is x .* x a problem?

3 Likes

Thank you.
Actually, there is no problem with x .* x. I just thought that it’s not intuitive to me (as it is not of my coding pattern).
BTW, make it Matrix seems nice :slight_smile:

My advice is to get used to the dot. In my opinion it’s one of the coolest and most powerful features of Julia.

2 Likes

Indeed :slight_smile:
Thank your for your advice.

Actually, the main reason I wanted to mutate a scalar variable is to make it compatible with in-place method of DifferentialEquations.jl, while not changing variable’s type (i.e., remaining it as scalar).
In my experience, changing type of variables make many troubles. For example, I may have to change previous codes. Or, I may have to restart Julia REPL.

One remedy that I just thought is to utilise ComponentArrays.jl and assign a scalar into a ComponentArray (I’m not sure it works for in-place method of DiffEq.jl when a component of ComponentArray is scalar).
I’ll give a try and share my experience.

I think this is probably not the best approach. Non-mutating operations on scalars are faster than mutating operations on arrays.

Scalars are not compatible with in-place versions of algorithms, and it’s better to not use them in that. Can’t you just use scalar versions?

1 Like

I hope so but I’ve not found a good way to use out-of-place method for SimulationLogger.jl, which is a convenient logging tool for DiffEq.
Unfortunately, I have to detour this issue till making it compatible with out-of-place (oop) method :frowning:

EDIT: hmm… maybe it’s the time to consider to make it compatible with oop method.

I see. I’m not familiar with those tools. If you are forced to use mutation anyway, you can look up Ref, and see if that helps.

1 Like

Thank you!