Index in position 2

조회 수: 9 (최근 30일)
Hunter Sylvester
Hunter Sylvester 2019년 3월 11일
편집: Cris LaPierre 2019년 3월 12일
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)')

채택된 답변

Cris LaPierre
Cris LaPierre 2019년 3월 11일
편집: Cris LaPierre 2019년 3월 12일
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
Cris LaPierre
Cris LaPierre 2019년 3월 12일
I put this link above. Just sliders and drop downs in 18a and 18b, but more coming soon!
madhan ravi
madhan ravi 2019년 3월 12일
Cool!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

madhan ravi
madhan ravi 2019년 3월 11일
for tdx = 2:length(t_vec)-1

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by