clearvars
f = 50;
omg = 2*pi*f;
t = linspace(0, 20, 1e5);
theta = linspace(0, 2*pi, 1e5);
vllrms = 400;
vll = vllrms*sqrt(2);
vln = vll/sqrt(3);
ph1 = vln*sin(theta);
ph2 = vln*sin(theta - 2*pi/3);
ph3 = vln*sin(theta + 2*pi/3);
figure()
hold on
plot(t, ph1)
plot(t, ph2)
plot(t, ph3)
legend('v_1n', 'v_2n', 'v_3n')
grid on
grid minor
xlabel('Time (ms)')
ylabel('V_{phase-neutral} (V)')
hold off

figure()
hold on
plot(t, ph1 - ph2)
plot(t, ph1 - ph3)
plot(t, ph2 - ph3)
plot(t, ph2 - ph1)
plot(t, ph3 - ph1)
plot(t, ph3 - ph2)
legend('v_{12}', 'v_{13}', 'v_{23}', 'v_{21}', 'v_{31}', 'v_{32}')
grid on
grid minor
xlabel('Time (ms)')
ylabel('V_{phase-phase} (V)')
hold off

maxArr = [];
for i = 1:1:1e5
    m = max([ph1(i) - ph2(i), ph1(i) - ph3(i), ph2(i) - ph3(i), ph2(i) - ph1(i), ph3(i) - ph1(i), ph3(i) - ph2(i)]);
    maxArr(end + 1) = m;
end

figure()
hold on
plot(t, maxArr)
grid on
grid minor
xlabel('Time (ms)')
ylabel('V_{out} (V)')
title('Output voltage waveform of the 3-phase rectifier')
hold off
saveas(gcf, 'rectifier.png')
avgVoltage = mean(maxArr)