Error - Array indices must be positive integers or logical values

3 次查看(过去 30 天)
I am trying to solve a wave equation of the form d2u/dt2-a2*d2u/dx2=0 and have the following code:
xstep = 0.1;
tstep = 0.05;
xstep2 = xstep*xstep;
tstep2 = tstep*tstep;
alpha = 2;
alpha2 = alpha*alpha;
lambda2 = alpha2*tstep2/xstep2;
xdomain = [0 1];
tdomain = [0 1];
nx = round((xdomain(2)-xdomain(1))/xstep);
nt = round((tdomain(2)-tdomain(1))/tstep);
u = zeros(nx+1,nx+1); % solutions
ustar = zeros(nx+1,1); % predictor step solution
dxdt0 = zeros(nx+1,1); % predictor step solution
%% initial condition
for i=1:nx+1
i = 0;
xi = (i-1)*xstep;
if(xi>=0 && xi<=1)
u(i,1) = sin(2*pi*xi); % initial condition , xt0(i)
dxdt0(i) = alpha*pi*sin(2*pi*xi);
u(i,2) = u(i,1) + dxdt0(i)*tstep; % using first order term for step 1 solution, xold(i), sol at tstep k
%u(i,2) = u(i,2) - 100*pi*pi*cos((xi-0.4)*10*pi)*tstep2*alpha2; % 2nd order correction
end
end
%% create dynamic plot
close all
x=linspace(xdomain(1),xdomain(2),nx+1);
h1=plot(x,xt0(:,t),'linewidth',2);
hold on;
h2=plot(x,xnew(:,t),'linewidth',2);
legend('Initital','Final');
xlabel('x [m]');
ylabel('Displacement [m]');
axis([0 1 -1 1]);
set(gca,'FontSize',16);
%% loop for time to obtain solution
for k=2:nt % loop for time t
time = k*tstep;
for i=1:nx+1 % loop for x
% Use periodic boundary condition, u(nx+1)=u(1)
if(i==1) % the left boundary
u(i,k+1) = 2*(1-lambda2)*u(i,k) + lambda2*(u(i+1,k)+u(nx+1,k)) - u(i,k-1);
elseif(i==nx+1) % the right boundary
u(i,k+1) = 2*(1-lambda2)*u(i,k) + lambda2*(u(1,k)+u(i-1,k)) - u(i,k-1);
else % the interior node
u(i,k+1) = 2*(1-lambda2)*u(i,k) + lambda2*(u(i+1,k)+u(i-1,k)) - u(i,k-1);
end
end
I get an error at line 38 (x, xt0(:,t)) that the "Index in position 2 is invalid. Array indices must be positive integers or logical values." I believe this is related to the for loop of the initial condition, but I am not entirely sure what to change to fix the problem.

回答(1 个)

Steven Lord
Steven Lord 2020-4-20
Looking at a section of your code:
i = 0;
xi = (i-1)*xstep;
if(xi>=0 && xi<=1)
u(i,1) = sin(2*pi*xi); % initial condition , xt0(i)
There's no such thing as row 0 in a numeric array in MATLAB. The first row is row 1.
You're trying to assign to the element in the first column of row 0 on the last line of that section of code I copied.
  1 个评论
Matlab12345
Matlab12345 2020-4-20
In that case, how would I assign the initial condition to u(i, 1)? If I set i = 1, I am told that "Array indices must be positive integers or logical values."

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by