# Array indices must be positive integers or logical values.

1 view (last 30 days)
Hazel Can on 24 May 2022
Edited: Hazel Can on 24 May 2022
Array indices must be positive integers or logical values.
y_m(i)=y_m(i-1)+0.5*h(3*f_m(t(i-1),y_m(i-1))-f_m(t(i-2),y_m(i-2)));
clc; clear all;
h=0.01;
t=0:h:1;
n=numel(t);
mu = 20;
f_m = @(t,y) mu*(y-cos(t))-sin(t);
exact = @(t) exp(mu*t)+cos(t);
%initials%
y_m(1)=exact(0);
y_m(2)=exact(h);
for i=3:n
y_m(i)=y_m(i-1)+0.5*h(3*f_m(t(i-1),y_m(i-1))-f_m(t(i-2),y_m(i-2)));
end
plot(t, exact(t));
hold
plot(t,y_m,'-o');
legend('Exact Solution','Midpoint Solution')
xlabel('t')
ylabel('y')
Lateef Adewale Kareem on 24 May 2022
Edited: Lateef Adewale Kareem on 24 May 2022
The problem is because you ar eindexing h instead of multiplying it.
Here is the correct version of the code.
clc; clear all;
h=0.01;
t=0:h:1;
n=numel(t);
mu = 20;
f_m = @(t,y) mu*(y-cos(t))-sin(t);
exact = @(t) exp(mu*t)+cos(t);
%initials%
y_m(1)=exact(0);
y_m(2)=exact(h);
for i=3:n
y_m(i)=y_m(i-1)+0.5*h*(3*f_m(t(i-1),y_m(i-1))-f_m(t(i-2),y_m(i-2)));
end
plot(t, exact(t));
hold
Current plot held
plot(t,y_m,'-o');
legend('Exact Solution','Midpoint Solution')
xlabel('t')
ylabel('y')

Lateef Adewale Kareem on 24 May 2022
here is another modification to make the code look exactly like the description
clc; clear all;
h = 0.01;
t = 0:h:1;
N = numel(t);
mu = 20;
% Exact Solution
exact = @(t) exp(mu*t)+cos(t);
%Initials Condition%
y = exact([0,h]);
% Derivative
f = @(i) mu*(y(i)-cos(t(i)))-sin(t(i));
for n = 3:N
y(n) = y(n-1) + 0.5*h*(3*f(n-1)-f(n-2));
f = @(i) mu*(y(i)-cos(t(i)))-sin(t(i));
end
plot(t, exact(t)); hold
Current plot held
plot(t,y,'-o');
legend('Exact Solution','Midpoint Solution')
xlabel('t')
ylabel('y')