% PhasorMovie.m
%
% Shows rotating stick in the complex plane whose shadow on the real axis
% is v(t)=Acos(wt+phi)
% A snapshot of the stick at t=0 is the phasor for v(t)
% Shows stick moving to right with shadow tracing out sinusoid.
% To save as .avi file:
% movie2avi(M,'PhasorMovie.avi','compression','None');

A = 1.5; % (V) Length of stick.
w = 2*pi; % (rad/s) rotations of stick per second.
phi = 30; % (deg) Phase shift.

frames_per_sec = 30; % (s^-1)
tilt = 30; % (deg) angle of tilt into page for 3-D view of x-axis

x_shadow3D = [0]; % Draw shadow of stick from origin to point on x-axis.
y_shadow3D = [0];
% Use 'for' loop for frames.
for ind_frame = 0:3*frames_per_sec % Three seconds at frames per second rate.
% Draw axes
plot([-2,8],[0,0],'k-') % t-axis
hold on
plot([0,0],[-2,2],'k-') % y-axis
[x_axis3D,y_axis3D] = three_D(tilt,[0,0],[-2,2],[0,0]); % x-axis end points.
plot(x_axis3D,y_axis3D,'k-') % x-axis

% Current time for this frame.
t = ind_frame/frames_per_sec;
% Draw unit circle in which stick rotates.
t_param = (2*pi)/60 * (1:60); % Array of times for parametric drawing of circle.
x_circ = cos(t_param);
y_circ = sin(t_param);

% Tilt circle into paper. Move to right by t.
[x_circ3D, y_circ3D] = ...
three_D(tilt,t*ones(1,length(t_param)),x_circ,y_circ);

% Plot circle in which phasor rotates.
plot(x_circ3D,y_circ3D,'b--') % Unit circle drawn in 3-D in blue.
axis('equal') % Use same scale in t and y directions.
axis([-2,8,-2,2]) % t axis from -2 to 8 and y axis is from -2 to 2 in 2-D
% projection. Format is axis([XMIN,XMAX,YMIN,YMAX]).

% Rotate phasor around circle at rate w.
x_stick = A*cos(w*t+phi*pi/180);
y_stick = A*sin(w*t+phi*pi/180);
t_stick = t;
% Project stick into 3-D.
[x_stick3D, y_stick3D] = three_D(tilt,t_stick,x_stick,y_stick);
plot([t,x_stick3D],[0,y_stick3D],'g-')
% Show waveform for shadow of stick. y=0 for stick.
[x_shadow3Dt, y_shadow3Dt] = three_D(tilt,t_stick,x_stick,0);
% Add another point to the waveform for the shadow waveform.
x_shadow3D = [x_shadow3D, x_shadow3Dt];
y_shadow3D = [y_shadow3D, y_shadow3Dt];
% Show the whole waveform of the shadow up to present time.
plot(x_shadow3D,y_shadow3D,'r-')
% Draw vertical from end of stick to end of shadow (t = now) in yellow.
plot([x_stick3D, x_shadow3Dt],[y_stick3D, y_shadow3Dt],'y-')
% Get the frames for making a movie.
M(ind_frame+1) = getframe(gcf);
% Slow down the frame rate when running the movie directly in Matlab.
pause(0.2)
% For the initial position, hold the picture for 2.8 seconds.
if ind_frame == 0
x_stick3D = x_stick3D
y_stick3D = y_stick3D
pause(2.8)
end
% Draw the entire picture again next time.
hold off
end