Index in position 1 is invalid. Array indices must be positive integers or logical values.
2 次查看(过去 30 天)
显示 更早的评论
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in midpointfinal (line 21)
k1 = h.*f_m(t(1),y_m(:,1));
clc; clear all;
t=0:0.01:1;
h=0.01;
n=(t(2)-t(1))/h;
alpha=0.5;
%initials%
y_m(1)=2;
y_m(2)=exp(20.*h)+cos(h);
f_m(1)=20.*(y_m(1)-cos(t(1)))-sin(t(1));
f_m(2)=20.*(y_m(2)-cos(t(2)))-sin(t(2));
%Midpoint Two step method%
for i=3:n
y_m(i)=y_m(i-2)+2.*h.*f_m(i-1);
f_m(i)=20.*(y_m(i)-cos(t(i)))-sin(t(i));
end
% Initialization with second order Runge-Kutta method
k1 = h.*f_m(t(1),y_m(:,1));
k2 = h.*f_m(t(1)+alpha.*h, y_m(:,1)+alpha.*k1);
y_m(:,2) = y_m(:,1) + (1-1/2/alpha).*k1 + k2/2/alpha;
1 个评论
Torsten
2022-5-23
f_m in your code is an array, not a function. Thus setting
k1 = h.*f_m(t(1),y_m(:,1));
k2 = h.*f_m(t(1)+alpha.*h, y_m(:,1)+alpha.*k1);
where f_m is used as a function makes no sense.
回答(2 个)
James Tursa
2022-5-23
Looks like you changed the definition of what f_m is in your code. In these lines f_m appears to be an array intended to hold values:
f_m(1)=20.*(y_m(1)-cos(t(1)))-sin(t(1));
f_m(2)=20.*(y_m(2)-cos(t(2)))-sin(t(2));
But in these lines f_m appears to be a function handle intended to evaluate a derivative:
k1 = h.*f_m(t(1),y_m(:,1));
k2 = h.*f_m(t(1)+alpha.*h, y_m(:,1)+alpha.*k1);
You need to fix up your nomenclature.
0 个评论
Voss
2022-5-23
t(1) is 0
t=0:0.01:1;
t(1)
and 0 is not a valid index in MATLAB
f_m = [1 2];
f_m(t(1))
It looks more like you're using f_m as if it were a function.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!