EE342: MATLAB M-FILE FOR RECURSIVELY SOLVING DIFFERENCE EQUATION APPROXIMATION OF NONLINEAR PENDULUM DIFFERENTIAL EQUATION

MATLAB M-File example5.m:
%
% Filename: example5.m
%
% Description: M-file for simulating pendulum using difference
%              equation obtained from nonlinear model.
%

clear;                          % clear memory

theta_init = 0.1;               % initial position
theta_dot_init = 0.2;           % initial velocity

T = [0.01 0.05 0.25];           % vector of sample intervals to be used

for n=1:3,                      % run simulation three times for
                                % different sample intervals
  
  tfinal = 15;                  % simulation time
  N = tfinal/T(n);              % number of samples to simulate over

  theta_prev1 = T(n)*theta_dot_init + theta_init; % IC theta[1] for recursion
  theta_prev2 = theta_init;                       % IC theta[0] for recursion

  kvec(1) = 0; kvec(2) = 1;     % load ICs into vectors for plotting
  thetavec(1) = theta_prev2;    % since loop starts at k = 2
  thetavec(2) = theta_prev1;

  for k = 2:N,                  % enter recursion loop

    if((k >= (2+2/T(n))) & (k < (2+7/T(n)))), % define input torque
      torque_prev2 = 5;
    else
      torque_prev2 = 0;
    end
                                % difference equation being solved
    theta = (2-T(n))*theta_prev1 + (T(n)-1)*theta_prev2 + ...
            10*T(n)*T(n)*sin(theta_prev2) + T(n)*T(n)*torque_prev2;
            
    theta_prev2 = theta_prev1;  % store previous values for next
    theta_prev1 = theta;        % iteration

    kvec(k+1) = k;
    thetavec(k+1) = theta;

  end;
  
  figure(n); clf;               % plot resulting response
  plot(kvec*T(n),thetavec,'o'); grid;
  xlabel('t = kT (sec)'); ylabel('\theta[k] (rad)');
  ttlevec=['Pendulum Simulation with T = ', num2str(T(n))];
  title(ttlevec);
  
  kvec = 0; thetavec = 0;       % reset/clear vectors

end;
MATLAB Plots Generated: