Index in position 2

6 visualizzazioni (ultimi 30 giorni)
Hunter Sylvester
Hunter Sylvester il 11 Mar 2019
Modificato: Cris LaPierre il 12 Mar 2019
I am trying to create a Dufort Frankel Finite Difference Scheme. I keep getting an error that says "Index in position 2 is invalid. Array indices must be positive integers or logical values." I think I understand that Matlab must start at 1 and that my tdx-1 messes this up. I have tried several things to change this but I am having trouble getting it to work. Could someone inform me of how to correct this issue?
%%%%% dT/dt = d^2T/dx^2 - partial derivatives
%%%% T = temperature = f(x,t)
%%%%% time derivative = second spatial derivative
%%%%(T(x,t+dt) - T(x,t))/dt = (T(x+dx,t) - 2*T(x,t) + T(x-1,t))/ dx^2
%%% Propagate this system in time
%%%% Solve for T(x,t+dt) =T(x,t) + k*dt/dx^2 * (T(x+dx,t) - 2*T(x,t) +
%%%% T(x-1,t))
%%%% length of the pipe
k = 2;
L = 10;
N = 10;
x_vec = linspace(0,L,N);
dx = x_vec(2)-x_vec(1);
dt = 0.5*(dx^2)/(2*k);
t_vec = 0:dt:10;
T_mat = zeros(length(x_vec),length(t_vec));
T_mat(1,:) = 200;
T_mat(end,:) = 150;
for tdx = 1;length(t_vec)-1;
for idx = 2:length(x_vec)-1
T_mat(idx,tdx+1) = T_mat(idx,tdx-1) + 2*k*dt/dx^2*( T_mat(idx+1,tdx) - (T_mat(idx,tdx+1)+T_mat(idx,tdx-1)) + (T_mat(idx-1,tdx)));
end
end
[tt,xx] = meshgrid(t_vec,x_vec);
mesh(xx,tt,T_mat)
xlabel('X coordinate (m)')
ylabel('Time (sec)')
zlabel('Temperature (F)')

Risposta accettata

Cris LaPierre
Cris LaPierre il 11 Mar 2019
Modificato: Cris LaPierre il 12 Mar 2019
The ";" instead of ":" is one issue as madhan ravi pointed out. However, another issue is with your indexing of tdx in your for loop.
for tdx = 1:length(t_vec)-1
for idx = 2:length(x_vec)-1
T_mat(idx,tdx+1) = T_mat(idx,tdx-1) + 2*k*dt/dx^2*( T_mat(idx+1,tdx) - (T_mat(idx,tdx+1)+T_mat(idx,tdx-1)) + (T_mat(idx-1,tdx)));
end
end
Note that your 2nd index for T_mat is sometimes tdx-1. But you start with tdx=1. As you point out, MATLAB indexes starting at 1, so this is throwing an error.
Did you perhaps get your idx and tdx backwards? You start with idx=2.
  13 Commenti
Cris LaPierre
Cris LaPierre il 12 Mar 2019
I put this link above. Just sliders and drop downs in 18a and 18b, but more coming soon!
madhan ravi
madhan ravi il 12 Mar 2019
Cool!

Accedi per commentare.

Più risposte (1)

madhan ravi
madhan ravi il 11 Mar 2019
for tdx = 2:length(t_vec)-1

Community Treasure Hunt

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

Start Hunting!

Translated by