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 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2019-12-5
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)

请先登录,再进行评论。

回答(1 个)

JESUS DAVID ARIZA ROYETH
编辑:JESUS DAVID ARIZA ROYETH 2019-12-5
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

类别

Help CenterFile Exchange 中查找有关 Particle & Nuclear Physics 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by