Array indices must be positive integers or logical values.
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Lateef Adewale Kareem
2022-5-24
编辑:Lateef Adewale Kareem
2022-5-24
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
plot(t,y_m,'-o');
legend('Exact Solution','Midpoint Solution')
xlabel('t')
ylabel('y')
采纳的回答
Lateef Adewale Kareem
2022-5-24
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
plot(t,y,'-o');
legend('Exact Solution','Midpoint Solution')
xlabel('t')
ylabel('y')
0 个评论
更多回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!