I tried to solve 6 couple differential equation, and getting an error which is " Index exceeds the number of array elements. Index must not exceed 2."

조회 수: 1 (최근 30일)
%how to remove this error " Index exceeds the number of array elements. Index must not exceed 2."
close all;
clc;
format long;
I1 = 0.2
I1 =
0.200000000000000
I2 = 0.8
I2 =
0.800000000000000
o = 3;
tc = 30E-9;
tf = 230E-6;
a1 = 0.1;
a2 =0.1;
P1 = 0.2;
P2 =0.2;
k= 0.17;
f=@(t,y) [(1/tc).*(y(3)- a1).*y(1)+(k./tc).*y(2).*cos(y(5));
(1/tc).*(y(4)- a2).*y(1)+(k./tc).*y(1).*cos(y(5)) ;
(1/tf).*(P1 - y(3).*(I1+1));
(1/tf).*(P2 - y(4).*(I2+1));
o - (k./tc).*((y(1)./y(2)) + (y(1)./y(2))).*sin(y(5))
];
[x,y]=runge_kutta_4(f,[0,5],[1,1,1,1,1],0.1);
Index exceeds the number of array elements. Index must not exceed 2.

Error in solution>runge_kutta_4 (line 49)
x = tspan(1):h:tspan(6);
plot(x,y);
title('When Time Step is 0.1');
legend('x(t)', 'y(t)', 'z(t)', 'Location', 'NorthEast')
xlabel('t')
ylabel('Solutions')
figure;
hold on;
for h=[0.1, 10^-3, 10^-6]
[x,y]=runge_kutta_4(f,[0,5],[1,1,1,1,1],h);
plot(x,y(:,1));
end
title('Plot of x(t) for 3 Different Time Steps');
xlabel('t')
ylabel('x(t)')
function [x,y]=runge_kutta_4(f,tspan,y0,h)
x = tspan(1):h:tspan(6);
y = zeros(length(x),5);
y(1,:) = y0;
for i=1:(length(x)-1)
k_1 = f(x(i),y(i,:));
k_2 = f(x(i)+0.5*h,y(i,:)+0.5*h*k_1);
k_3 = f((x(i)+0.5*h),(y(i,:)+0.5*h*k_2));
k_4 = f((x(i)+h),(y(i,:)+k_3*h));
y(i+1,:) = y(i,:) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
end
end

채택된 답변

Walter Roberson
Walter Roberson 2022년 7월 2일
x = tspan(1):h:tspan(6);
That line is expecting that tspan is a vector or array with at least 6 elements
Working backwards
function [x,y]=runge_kutta_4(f,tspan,y0,h)
tspan is coming from the second parameter of the call
[x,y]=runge_kutta_4(f,[0,5],[1,1,1,1,1],h);
which is [0,5] -- which only has two elements, not at least 6.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by