# My code keeps saying the variable u appears to be changing as well as index exceeds the number of array elements(1). Could someone help me with this

1 view (last 30 days)
L = 1 % length of domain in x direction
tmax = 10 % end time
nx = 11 % number of nodes in x direction
nt = 101 % number of time steps dx = L/(nx-1);
dt = tmax/(nt-1);
alpha = 0.02
r = alpha*dt/dx^2;
r2 = 1 - 2*r;
t = 0
u = 0 % initial condition
for m=1:nt
uold = u; % prepare for next step
t = t + dt;
for i=2:nx-1
u(i) = r*uold(i-1) + r2*uold(i) + r*uold(i+1); %%This is where the issue is
end
end

#### 1 Comment

Walter Roberson on 5 Dec 2019
u = 0 % initial condition
A scalar
uold = u; % prepare for next step
copies the scalar
for i=2:nx-1
i starts from 2
u(i) = r*uold(i-1) + r2*uold(i) + r*uold(i+1); %%This is where the issue is
needs uold(i-1) and uold(i) and uold(i+1) which starts as uold(1), uold(2), uold(3), but uold is only a scalar.
Maybe you should initialize
u = zeros(1,nx);
but if you do, then be aware that you are going to be reading from those 0's as you go. That might be acceptable for something like heat propagation (though if you are doing heat, watch out for units: sometimes you should be using Kelvin instead of Celcius)

JESUS DAVID ARIZA ROYETH on 5 Dec 2019
Edited: JESUS DAVID ARIZA ROYETH on 5 Dec 2019
correction:
L = 1 % length of domain in x direction
tmax = 10 % end time
nx = 11 % number of nodes in x direction
nt = 101 % number of time steps dx = L/(nx-1);
dt = tmax/(nt-1);
alpha = 0.02
r = alpha*dt/dx^2;
r2 = 1 - 2*r;
t = 0
u = zeros(1,nx); % initial condition
for m=1:nt
uold = u; % prepare for next step
t = t + dt;
for i=2:nx-1
u(i) = r*uold(i-1) + r2*uold(i) + r*uold(i+1); %%This is where the issue is
end
end7