Array indices must be positive integers or logical values.

1 view (last 30 days)
Array indices must be positive integers or logical values.
Error in adambashforthalternatif (line 14)
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)));
%% Adam-Bashforth %%
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);
%Adam-Bashforth method%
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')
  1 Comment
Lateef Adewale Kareem
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.
%% Adam-Bashforth %%
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);
%Adam-Bashforth method%
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')

Sign in to comment.

Accepted Answer

Lateef Adewale Kareem
Lateef Adewale Kareem on 24 May 2022
here is another modification to make the code look exactly like the description
%% Adam-Bashforth %%
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));
%Adam-Bashforth method%
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')

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!