Filter löschen
Filter löschen

Index in position 1 exceeds array bounds. Index must not exceed 1000.

3 Ansichten (letzte 30 Tage)
When I run this program I get an error by line 44 saying "Index in position 1 exceeds array bounds. Index must not exceed 1000."
Can somebody please explain to me what this error means and how to fix it?
M=1000;
dx=.02;
Tmax=10;
dt=.01;
N=Tmax/dt; %number of time steps
h0=0.1;
g=9.81;
St=.1;
Cf=0.005;
W=1;
%Creating an arrays for A,h,u,B,C
h=zeros(M,N);
A=zeros(M,N);
u=zeros(M,N);
B=zeros(M,N);
C=zeros(M,N);
%Initial Conditions
for n=1
for i=1:M %for t=0 aka n=1
h(i,n)=h0; %the height of the water is given at h0
A(i,n)=0; %the speed of the water is 0 tf A=0
u(i,n)=A(i,n)./h(i,n);
B(i,n)=h(i,n).*(u(i,n)).^2+g.*h(i,n).^2./2;
C(i,n)=-St.*g.*h(i,n)-(Cf.*u(i,n).*abs(u(i,n))/2).*(W+2.*h(i,n))./W;
end
end
%Left Boundry
for n=1:N-1
h(1,n+1)=h(2,n)-(dt./dx).*A(2,n);
A(1,n+1)=0;
u(1,n+1)=A(1,n+1)./h(1,n+1);
B(1,n+1)=h(1,n+1).*(u(1,n+1)).^2+g.*h(1,n+1).^2./2;
C(1,n+1)=-St.*g.*h(1,n+1)-(Cf.*u(1,n+1).*abs(u(1,n+1))/2).*(W+2.*h(1,n+1))./W;
end
%Main Equations
for n=1:N-1
for i=2:M
h(i,n+1)=.5.*(h(i+1,n)+h(i-1,n))-(dt./2.*dx).*(A(i+1,n)-A(i-1,n));
A(i,n+1)=.5.*(A(i+1,n)+A(i-1,n))-(dt./2.*dx).*(B(i+1,n)-B(i-1,n))+.5.*(C(i+1,n)+C(i-1,n)).*dt;
u(i,n+1)=A(i,n+1)./h(i,n+1);
B(i,n+1)=h(i,n+1).*(u(i,n+1)).^2+g.*h(i,n+1).^2/2;
C(i,n+1)=-St.*g.*h(i,n+1)-(Cf.*u(i,n+1).*abs(u(i,n+1))./2).*(W+2.*h(i,n+1))./W;
end
end
%Right Boundry
for n=1:N-1
h(M,n+1)=h(M-1,n)+(dt./dx).*A(M-1,n);
A(M,n+1)=0;
u(M,n+1)=A(M,n+1)./h(M,n+1);
B(M,n+1)=h(M,n+1).*(u(M,n+1)).^2+g.*h(M,n+1).^2./2;
C(M,n+1)=-St.*g.*h(M,n+1)-(Cf.*u(M,n+1).*abs(u(M,n+1))./2).*(W+2.*h(1,n+1))./W;
end

Akzeptierte Antwort

Voss
Voss am 16 Mai 2022
%Main Equations
for n=1:N-1
for i=2:M
h(i,n+1)=.5.*(h(i+1,n)+h(i-1,n))-(dt./2.*dx).*(A(i+1,n)-A(i-1,n));
% ...
end
end
When i == M, the code will try to access h(i+1,n), which is h(M+1,n), which will fail and generate the error because h has only M rows. (Similarly for A(i+1,n) later on that same line.)
Changing the for loop to for i=2:M-1 avoids this problem and allows the code to run completely without throwing any errors, and that seems like it's probably the correct thing to do, since h(M,:), A(M,:), etc., are calculated in the next section ("Right Boundry").

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by