One MATLAB code for solving pendulum equation $\ddot{\theta} + \sin{\theta} = 0$ is:
T=100;
h=0.1; n=floor(T/h);
y0 = [1 0];
y=y0; sol=y0;
for nT = 1:2
theta = y(1);
y(1) = y(1) + h*y(2);
y(2) = y(2) - h*sin(theta);
sol = [sol;y];
end
My question is how can I write the code for an alternative algorithm:
${\theta}_{n+1} = {\theta}_{n} + h{\omega}_{n}; {\omega}_{n+1} = {\omega}_{n} - h\sin({\theta}_{n+1})$
where ${\omega} = \dot{\theta}$.
How can I define omega as the first derivate in MATLAB (without using symbolic toolbox). Or is there any other way?
I tried to write the code:
T=100;
h=0.1; n=floor(T/h);
theta0 = [1 0];
theta = theta0; sol = theta0;
for nT = 1:n
theta = theta + h*omega;
omega = omega - h*sin(theta);
end
But because I have not yet defined omega, an error occur.
Help is very much appreciated. Thanks in advance!
Your first code is almost there. Just use
y(2)=y(2)-h*sin(y(1))
instead of
y(2)=y(2)-h*sin(theta).
No matter what method you use, you are simply going to have to provide an initial y(2) in addition to the initial y(1). This is what is called a second order equation, and they always need initial values and initial first derivatives.