'Julia variable disappears/changes
I have the following MWE
function f(p)
ans = zeros(p, 2)
return ans
end
ans = f(2)
ans
b=ans.+1.0
ans
At first, ans is correct, but the operation creating b overwrites ans.
julia> ans = f(2)
2×2 Matrix{Float64}:
0.0 0.0
0.0 0.0
julia> ans
2×2 Matrix{Float64}:
0.0 0.0
0.0 0.0
julia> b=ans.+1.0
2×2 Matrix{Float64}:
1.0 1.0
1.0 1.0
julia> ans
2×2 Matrix{Float64}:
1.0 1.0
1.0 1.0
It's a fresh install of julia 1.6.5.
The same thing happens if I just ask typeof(ans). The value of ans itself changes to the output of typeof(ans) which is a DataType.
julia> ans=f(2)
2×2 Matrix{Float64}:
0.0 0.0
0.0 0.0
julia> typeof(ans)
Matrix{Float64} (alias for Array{Float64, 2})
julia> typeof(ans)
DataType
Any ideas?
Solution 1:[1]
See the docstring of ans:
help?> ans
ans
A variable referring to the last computed value, automatically set at the interactive prompt.
So as you can see Julia REPL automatically overwrites ans after each evaluation of an expression.
In short it is recommended not to use ans in a global scope in interactive sessions (except to get the result of last operation).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bogumił Kamiński |
