MATLAB: What’s wrong with the code

differential equation

function dxdt = pendulum(t,x)
L = 1;
theta = x(1);
gamma = x(2);
dtheta = gamma;
dgamma = -(9.8/L)*sin(theta);
dxdt = zeros(2,1);
dxdt(1)=dtheta;
dxdt(2)=dgamma;
[t,x]=ode45('pendulum',[0 10],[0.9*pi 0]);
plot(t,x(:,1));
hold on;
plot(t,x(:,2),'r');
legend('Position','Velocity');
plot(x(:,1),x(:,2));
xlabel('Position');
yLabel('Velocity');
It says x is undefined

Best Answer

There is no error in your code, the problem is the way you are using it.
Save the followed code as pendulum.m
function dxdt = pendulum(t,x)
L = 1;
theta = x(1);
gamma = x(2);
dtheta = gamma;
dgamma = -(9.8/L)*sin(theta);
dxdt = zeros(2,1);
dxdt(1)=dtheta;
dxdt(2)=dgamma;
Then in another file write and run this code
[t,x]=ode45('pendulum',[0 10],[0.9*pi 0]);
plot(t,x(:,1));
hold on;
plot(t,x(:,2),'r');
legend('Position','Velocity');
plot(x(:,1),x(:,2));
xlabel('Position');
ylabel('Velocity');