What's wrong with my code?

1 次查看(过去 30 天)
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
  2 个评论
dpb
dpb 2014-5-18
Need EXACT error in context including traceback to be able to tell--too many places where x is used. You may well need to change the internal use of x as the result of ode45 and where it's the passed-in value; didn't try to read the code thoroughly enough to tell for certain.

请先登录,再进行评论。

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2014-5-18
编辑:Azzi Abdelmalek 2014-5-18
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');
  3 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2014-5-18
Andrew, what about your original question?
Andrew Davies
Andrew Davies 2014-5-18
That was an example from a textbook and i was using it to try to understand how to solve my own one, the second one i described

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Particle & Nuclear Physics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by