Hi Community! I am practicing solving a basic one-dimensional diffusion equation in Julia and hoping to get familiar with Julia asap.
I fixed up the local scope parameters by using ‘global’ to define ‘u’ and ‘b’ in my loop. However, no plots were returned after I ran my codes. Could you please give me some advice? I would really appreciate your help!
##solve the very basic 1-D diffusion equation with no-flux BC on left and right sides.
using DifferentialEquations
using Plots
using LinearAlgebra
using Latexify
L=1.0
NX=500
dx=L/NX
nx=NX+1
x=(0:NX)*dx
sigma=L/16
u=1/(sigmasqrt(2pi))exp.(-0.5(x/sigma).^2) #initial value: Gaussian function
plot(x,u,color=“blue”)
#####solving the PDE
for m in 1:1:nsteps
global b=[0; (alphau[1:nx-2]+2(1-alpha)u[2:nx-1]+alphau[3:nx]); 0]
global u=A\b
if mod(m,100)==0
plot!(x,u,color=“red”)
end
end
Unrelated to this, I would recommend you stop working in global scope as that’s terrible for performance, and bad practice in general. It looks like the parameters that vary in your code are L, NX, D, and nsteps, so you can do
function solve_pde(L, NX, D, nsteps)
# your code here
end
you can then either return the plot from this function as I said above, or do display(p) in your function if you just want to show it without returning anything.
(Also no need to do 1:1:nsteps, 1:nsteps will do as 1 is the default step)
Hi Nishg! Thanks for your advice! I tried and it runs faster! Unrelated to this question, I found that sometimes I changed the parameters or even deleted the plot syntax, Julia still returns the old results and plots. Why would this happen and how should I correctly use Julia?
Is there a workspace in Julia, just as what Matlab does? For example, after I run the codes, all solutions and parameters are stored temporarily in ‘workspace’, including the parameter x. Even if I delete the syntaxes relative to x, the value of x can still be called. Can I empty the ‘workspace’ and where is it if it exists?
(I just testified some simple examples. The ‘workspace’ does exist. if I define a=12, b=13, c=a+b. Run. Then, delete all syntaxes. Display(c). It returns 25.)
Without going into too much detail about modules, namespaces etc. the short answer is no, there’s nothing like clear in Matlab. Which is another reason to keep your code in functions and not pollute the global namespace with lots of definitions.