Index in position 1 is invalid. Array indices must be positive integers or logical values.

조회 수: 3 (최근 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
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
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.

Voss
Voss 2022년 5월 23일
t(1) is 0
t=0:0.01:1;
t(1)
ans = 0
and 0 is not a valid index in MATLAB
f_m = [1 2];
f_m(t(1))
Array indices must be positive integers or logical values.
It looks more like you're using f_m as if it were a function.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by