Current location - Education and Training Encyclopedia - Educational Knowledge - Urgent! ! ! Solving ordinary differential equations by fourth-order Runge-Kutta method in matlab
Urgent! ! ! Solving ordinary differential equations by fourth-order Runge-Kutta method in matlab
Create a. m file.

-

Function? θ = Danbai (t, x)

X = X( 1);

dx = X(2);

ddx =-sin(x);

theta =[dx; ddx];

-

Command window input

& gt& gt? [t, Y]= ode 45(@ Danbai, [0? 6],[pi/3? - 1/2]);

& gt& gt? plot(t,Y(:, 1),' ro-',t,Y(:,2),' bv-');

& gt& gt? Legend ('\theta-t', \theta-t')?

Self-edited runge kuta

-

Function? [y, z]= rungekuta (a, b, y0, z0, h)

x = a:h:b;

y( 1)= y0;

z( 1)= z0;

n =(b-a)/h+ 1;

For what? i=2:n

K( 1, 1)=f 1(x(i- 1),y(i- 1),z(I- 1));

K(2, 1)=f2(x(i- 1),y(i- 1),z(I- 1));

K( 1,2)=f 1(x(i- 1)+h/2,y(i- 1)+K( 1, 1)*h/2,z(i- 1)+K(2, 1)* h/2;

K(2,2)=f2(x(i- 1)+h/2,y(i- 1)+K( 1, 1)*h/2,z(i- 1)+K(2, 1)* h/2);

K( 1,3)=f 1(x(i- 1)+h/2,y(i- 1)+K( 1,2)*h/2,z(i- 1)+K(2,2)* h/2);

K(2,3)=f2(x(i- 1)+h/2,y(i- 1)+K( 1,2)*h/2,z(i- 1)+K(2,2)* h/2);

K( 1,4)=f 1(x(i- 1)+h,y(i- 1)+K( 1,3)*h,z(i- 1)+K(2,3)* h);

K(2,4)=f2(x(i- 1)+h,y(i- 1)+K( 1,3)*h,z(i- 1)+K(2,3)* h);

y(I)= y(I- 1)+h/6 *(K( 1, 1)+2*K( 1,2)+2*K( 1,3)+K( 1,4));

z(I)= z(I- 1)+h/6 *(K(2 1)+2 * K(2,2)+2*K(2,3)+K(2,4));

end

y(2)

plot(y,' r ')? %θ-t graph

Keep? exist

plot(f 1(x,y,z),' g ')? %? Dθ-t diagram

Keep? exist

Plot(f2(x, y, z),' b-')%d2θ-t graph

%f 1.m

Function? f 1=f 1(x,y,z)

f 1 = z;

%f2.m

Function? f2=f2(x,y,z)

F2 =-sin(y);

-

Rungekuta (0,6, pi/3,-1/2,0.02)