clc; clear

n = 100;

% Naponot i strujata se vo faza
u = @(t) 5*sin(100*pi*t);
i = @(t) 3*sin(100*pi*t);
p = @(t) u(t).*i(t);
figure
fplot(u, [0 0.06], n, LineWidth=1.5); hold on
fplot(i, [0 0.06], n, LineWidth=1.5);
fplot(p, [0 0.06], n, LineWidth=1.5);
Psr = integral(p, 0 , 0.06) / 0.06;
plot([0 0.06], [Psr Psr], LineWidth=2); hold off
ylim([-10 25]); grid
fprintf('Naponot i strujata se vo faza, Psr = %.3f W\n',Psr);

% Strujata docni za 60 stepeni zad naponot
poz = @(x) x >= 0; % ima vrednost 1 ako x e pozitiven broj
neg = @(x) x < 0; %  ima vrednost 1 ako x e negativen broj
u = @(t) 5*sin(100*pi*t);
i = @(t) 6*sin(100*pi*t-pi/3);
p = @(t) u(t) .* i(t);
p_poz = @(t) p(t) .* poz(p(t));
p_neg = @(t) p(t) .* neg(p(t));
figure
fplot(u, [0 0.06], n, LineWidth=1.5); hold on
fplot(i, [0 0.06], n, LineWidth=1.5);
fplot(p, [0 0.06], n, LineWidth=1.5);
Psr = integral(p, 0 , 0.06) / 0.06;
Psr_poz = integral(p_poz, 0 , 0.06) / 0.06;
Psr_neg = integral(p_neg, 0 , 0.06) / 0.06;
plot([0 0.06], [Psr Psr], LineWidth=2);
plot([0 0.06], [Psr_poz Psr_poz], LineWidth=2);
plot([0 0.06], [Psr_neg Psr_neg], LineWidth=2); hold off
ylim([-10 25]); grid
fprintf('Strujata docni za 60 stepeni zad naponot, Psr = %.3f W, Psr_poz = %.3f W, Psr_neg = %.3f W.\n',Psr,Psr_poz,Psr_neg);

% Strujata docni za 90 stepeni zad naponot
u = @(t) 5*sin(100*pi*t);
i = @(t) 6*sin(100*pi*t-pi/2);
p = @(t) u(t) .* i(t);
p_poz = @(t) p(t) .* poz(p(t));
p_neg = @(t) p(t) .* neg(p(t));
figure
fplot(u, [0 0.06], n, LineWidth=1.5); hold on
fplot(i, [0 0.06], n, LineWidth=1.5);
fplot(p, [0 0.06], n, LineWidth=1.5);
Psr = integral(p, 0 , 0.06) / 0.06;
Psr_poz = integral(p_poz, 0 , 0.06) / 0.06;
Psr_neg = integral(p_neg, 0 , 0.06) / 0.06;
plot([0 0.06], [Psr Psr], LineWidth=2);
plot([0 0.06], [Psr_poz Psr_poz], LineWidth=2);
plot([0 0.06], [Psr_neg Psr_neg], LineWidth=2); hold off
ylim([-25 25]); grid
fprintf('Strujata docni za 90 stepeni zad naponot, Psr = %.3f W, Psr_poz = %.3f W, Psr_neg = %.3f W.\n',Psr,Psr_poz,Psr_neg);