functionjulia

Julia function unwittingly modifies its argument without ! - help me understand this behaviour?


I do not understand this behaviour of Julia. Somehow, the arrays xit and mut are connected at the hip and share values in the following MWE below:

sample_size = 100;
mc_reps = 100;
ka = .01;
threshold=1;
mut = Array{Float64}(undef,mc_reps,sample_size);
xit = mut;
mut[:,1] = ones(mc_reps);
function regime_prob(ka,ce,muu)
   h = 1/(1+ exp(ka*(ce-muu)))
   return h
end
xit[1,1] = regime_prob(ka,threshold,mut[1,1]);
xit[:,1] = regime_prob.(ka,threshold,mut[:,1]);

I tried declaring the function inline like so: regime_prob(ka,ce,muu) = 1/(1+ exp(ka*(ce-muu)));

which made no difference. Is there a subtle idiom I am invoking unwittingly?

I expected the mut array to keep its columns of ones but somehow the value of the xit keeps getting written into it.


Solution

  • In case this doesn't get closed as a duplicate, the correct answers are hiding in the comments to your question:

    1. Assignment in Julia does not copy, so xit = mut means xit is now just another name referring to the same object as mut:
    julia> x = rand(5); y = x;
    
    julia> x === y
    true
    
    1. If you do want to copy, use copy(mut)

    2. The ! suffix to a function name in Julia is just a syntactical convention - you can write a myfunction(x) that mutates x just as well as a myfunction!(x) that doesn't, but both of these are discouraged because they are likely to confuse the reader.