# What wrong in line 12 ?? help me please (Index exceeds matrix dimensions.)

1 view (last 30 days)
Bui Thien Phuc on 9 Apr 2019
Edited: Torsten on 10 Apr 2019
clear
close all;
N=10;
h = 0.5;
u1(1)= 2 ;
u2(1)= 3 ;
u3(1)=0 ;
t(1) = 0;
for n=1:N
u3(n+1)=u1(n)+h*u2(1);
u1(n+1)=u1(n)+1/2*(4*exp(0.8*t(n))-0.5*u1(n)+4*exp(0.8*t(n+1))-0.5*u3(n));
t(n+1)= t(n) + h ;
end
plot(t,u1);

Alex Mcaulley on 9 Apr 2019
In this line:
u1(n+1)=u1(n)+1/2*(4*exp(0.8*t(n))-0.5*u1(n)+4*exp(0.8*t(n+1))-0.5*u3(n));
the length of t is n, then t(n+1) gives an error

Alex Mcaulley on 9 Apr 2019
Then, a better option is
clear
close all;
N=10;
h = 0.5;
u1 = zeros(1,N+1);
u2 = zeros(1,N+1);
u3 = zeros(1,N+1);
u1(1)= 2 ;
u2(1)= 3 ;
t = 0:h:h*N;
for n=1:N
u3(n+1)=u1(n)+h*u2(n);
u1(n+1)=u1(n)+1/2*(4*exp(0.8*t(n))-0.5*u1(n)+4*exp(0.8*t(n+1))-0.5*u3(n));
end
plot(t,u1);
Bui Thien Phuc on 9 Apr 2019
just answer me I want to use u2(1) only one time in first circle so I did right ?
Torsten on 10 Apr 2019
If you use your code: no.
If you use Alex's second code: yes.

Torsten on 9 Apr 2019
clear
close all;
N = 10;
h = 0.5;
u1(1) = 2 ;
u2(1) = 3 ;
u3(1) = 0 ;
t = 0:h:N*h;
for n = 1:N
u3(n+1) = u1(n)+h*u2(1);
u1(n+1) = u1(n)+1/2*(4*exp(0.8*t(n))-0.5*u1(n)+4*exp(0.8*t(n+1))-0.5*u3(n));
end
plot(t,u1);