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!