I create a simple MWE to demonstrate some kind of reference problem which is leading to unwanted behavior when creating matrices with function elements. Here is the code:
function test()
zfcts = Any[t -> 0., t -> 0.]
fcts = Any[t -> sin(t), t -> cos(t)]
g = Any[]
push!(g, zfcts)
push!(g, zfcts)
g[1][1] = fcts[1] # sin
g[2][1] = fcts[2] # cos
x = 2.1
@show g[1][1](x)
@show (g[2][1](x))
@show (g[1] === g[2]) # Should not be true!!! <<<<<<
@show (g[1][1] === g[2][1]) # true
@show (g[1][2] === g[2][2]) # true
@show (g[1][1] === g[1][2]) # true
@show (fcts[1] === fcts[2]) # false (as it should be)
end
test()
I expect
g[1][1] = sin(2.1)
g[2][[1] = cos(2.1)
However, the results are always the same, and equal to fcts[2]
, the second function define in the fcts
list. I thought that push!
did a copy.
Here is the code output:
> test()
((g[1])[1])(x) = -0.5048461045998576
((g[2])[1])(x) = -0.5048461045998576
g[1] === g[2] = true
(g[1])[1] === (g[2])[1] = true
(g[1])[2] === (g[2])[2] = true
(g[1])[1] === (g[1])[2] = false
fcts[1] === fcts[2] = false
false
As usual, any insight is appreciated. I feel as if I should understand this coming from a C++ background, but I clearly am missing something important about functions and push!
. Thanks.