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 visualización (últimos 30 días)
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 comentario
Walter Roberson
Walter Roberson el 5 de Dic. de 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)

Iniciar sesión para comentar.

Respuestas (1)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH el 5 de Dic. de 2019
Editada: JESUS DAVID ARIZA ROYETH el 5 de Dic. de 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

Categorías

Más información sobre Particle & Nuclear Physics en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by