Index exceeds number of array elements

clear all
clc
close all
y(1) = -100;
y_exact(1) = -100;
t0 = 0;
t_end = 10;
dt = 1/50;
t = t0:dt:t_end;
for i = length(t)-1
y(i+1) = y(i)+dt*(y0.*y(i)-y0^2*t(i+1));
y_exact(i+1) = 1+y0.*t(i+1)+(y0-1).*exp(y0.*t(i+1));
end
figure(1)
hold on
plot(t,y,'b-o')
plot(t,y_exact,'r')
When i run this I get an error message in line 12 (y(i+1)-line):
Index exceeds the number of array elements (1).
How can I avoid this?

回答(1 个)

I think you want this
for i = length(t)-1
to be this instead
for i = 1:length(t)-1
The way you have it currently coded, the index i takes on only one value inside the loop, namely length(t)-1, and those y elements don't exist yet.

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by