% demo 8_2
% using degrees as independent variable.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Square-wave operation.
% Purely resistive load with no back-emf.

% To save figure as vector image,
% go to "Print Preview" and set correct orientation (eg. landscape,
% fill page),
% then "Save As..." and pick pdf, svg etc...

t = linspace(0, 4*pi, 1000); % generate time var for two periods at frequency f.
theta = r2d(t) % calculate phase angle at time t.
fi = 120; % phase angle between phases.
R = 10; %ohm % purely arbitrary resistance for illustrative purposes.

VAN = (square(d2r(theta)) + 1)/2;
VBN = (square(d2r(theta) + d2r(fi)) + 1)/2;
VCN = (square(d2r(theta) + 2*d2r(fi)) + 1)/2;
VAn = 2/3 * VAN - 1/3 * (VBN + VCN);
VBn = 2/3 * VBN - 1/3 * (VAN + VCN)
VCn = 2/3 * VCN - 1/3 * (VAN + VBN)

m = 4; n = 2;
subplot(m, n, 1)
plot(theta, VAN) %plot with x axis normalized to n*pi
xticks(0:60:720);
xlabel('\theta');, ylabel('V_{AN}'); grid on;

subplot(m, n, 3)
plot(theta, VBN) %plot with x axis normalized to n*pi
xticks(0:60:720);
xlabel('\theta'); ylabel('V_{BN}'); grid on;

subplot(m, n, 5)
plot(theta, VCN) %plot with x axis normalized to n*pi
xticks(0:60:720); 
xlabel('\theta'); ylabel('V_{CN}'); grid on;

subplot(m, n, 2)
plot(theta, VAn)
xticks(0:60:720); yticks(-1:1/3:1); ytickformat('%.2f');
ylabel('V_{An}'); xlabel('\theta'); grid on;

subplot(m, n, 4)
plot(theta, VBn)
xticks(0:60:720); yticks(-1:1/3:1); ytickformat('%.2f');
ylabel('V_{Bn}'); xlabel('\theta'); grid on;

subplot(m, n, 6)
plot(theta, VCn)
xticks(0:60:720); yticks(-1:1/3:1); ytickformat('%.2f');
ylabel('V_{Cn}'); xlabel('\theta'); grid on;

id = (VAN.*VAn + VBN.*VBn + VCN.*VCn)/R;
subplot(m, n, [7,8])
plot(theta, id, theta, VAN.*VAn./10, theta, VBN.*VBn./10, theta, VCN.*VCn./R)
xticks(0:60:720); yticks(0:0.1/3:0.1); ytickformat('%.3f'); %ticks
ylabel('i_d'); xlabel('\theta This is the current when switches connected to P are active. R = 10\Omega'); %labels
grid on;
legend('show'); legend('i_d', 'I_{An}', 'I_{Bn}', 'I_{Cn}') %legend
suptitle('All amplitudes are normalized')