Hi Guys

Please refer to the below code. It was running perfectly and now for some reason I am getting the following error, “ERROR: UndefVarError: `sol` not defined”. Which makes no sense it has been defined…

Any assistance would be appreciated.

``````using Plots
using DifferentialEquations

function sdof!(dx,x,p,t)
m,k,c,f,w = p
dx[1] = x[2]
dx[2] = (-c*x[2]-k*x[1]+f*sin(w*t))/m
end

m =  [74.11,13.241,2.4,3.4,2.366]/100# [%]

f = 1000 # [N] forcing function
M = 611.778

tspan = (0,1)
x0 = [0.00,0.00]
T_displacement = zeros(length(tspan[1]:0.001:tspan[2]))

for i in 1:length(nf)
k = nf[i]^2*m[i]*M
c = 0.01*(m[i]*M+k)
p = m[i]*M,k,c,f,50*6.28
prob = ODEProblem(sdof!, x0, tspan, p)
sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8, saveat = 0.001)
T_displacement += sol[1,:]
end

plotly()

#plt_1 = plot()
display(plot(sol.t,T_displacement,xlabel = "Time (sec)", ylabel = "Displacement (m)"))

``````

`sol` is a local variable and is not defined in the global scope, see Scope of Variables · The Julia Language

Use `global sol = solve(...)`.

If you define a variable inside a loop, it’s not available outside the loop:

``````julia> for i in 1:10
x = 1
end

julia> x
ERROR: UndefVarError: `x` not defined
``````

The solution is to add `global`:

``````julia> for i in 1:10
global x = 1
end

julia> x
1
``````

It’s better style to put code into functions - it’ll run faster, and be more debuggable. If you do anything bigger than a throwaway script, or to quickly test something, I recommend doing that.

1 Like

Hi Guys

Thanks for the replies, I just figured out the issue a few minutes after posting.