Array indices must be positive integers or logical values.

1 visualizzazione (ultimi 30 giorni)
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 Commento
Lateef Adewale Kareem
Lateef Adewale Kareem il 24 Mag 2022
Modificato: Lateef Adewale Kareem il 24 Mag 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')

Accedi per commentare.

Risposta accettata

Lateef Adewale Kareem
Lateef Adewale Kareem il 24 Mag 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')

Più risposte (0)

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by