Why is my code not working??

1 view (last 30 days)
Alex
Alex on 4 May 2013
function [T , Y] = pendulum_RK4(f,tspan,y0,n)
% Solves y' = f(t,y) with initial condition y(a) = y0
% on the interval [a,b] using n steps of the 4th order runge kutta method.
% y and f may be column vectors
% Dimension y0 must equal that of y and f
% T shall be a n+1 column vector
% Y shall be a (n+1) by d matrix (d is the length of y)
a = tspan(1);
b = tspan(2);
% Step size:
h = (b-a)/n;
% t and y are current variables:
t = a; y = y0;
% T and Y will record all steps:
T = a; Y = y0';
for i = 1:n
k1 = h*f(t,y);
k2 = h*f(t+(0.5*h),y+(0.5*k1));
k3 = h*f(t+(0.5*h),y+(0.5*k2));
k4 = h*f(t+h,y+k3);
y = y + (1/6)*k1 + (1/3)*k2 + (1/3)*k3 + (1/6)*k4;
t = a + i*h;
T = [T; t];
Y = [Y; y'];
end
>> f = inline('[y(2);-9.81*sin(y(1))-(6.25*0.25)*cos(y(1))*sin(2.5*t)]','t','y')
>> [T Y] = pendulum_RK4(f,[0 10],[0;0],1000)
>> theta = Y(:,1);
>>plot(T,theta)
  1 Comment
Zhang lu
Zhang lu on 4 May 2013
it can work well in my computer
whats your error message?
do your M file in your matlab current folder ?

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!