Index exceeds number of array elements

1 view (last 30 days)
Iver Brekken
Iver Brekken on 2 Feb 2022
Answered: James Tursa on 2 Feb 2022
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?

Answers (1)

James Tursa
James Tursa on 2 Feb 2022
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.

Tags

Community Treasure Hunt

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

Start Hunting!