% Control3_2.m
% Solution to problem 2 of control 3. 2023/05/05
% Jose M. Soler

% Set values of resitances and source voltages
clear
V = [ 3; 2; 3 ];
R = [ 2; 1; 2; 2; 1; 0 ];
R6 = [0:0.01:3];

% Find circuit intensities and powers
nR6 = numel(R6);
for iR6 = 1:nR6
  R(6) = R6(iR6);
  [I(:,iR6),PR(:,iR6),PV(:,iR6)] = Circuit_C3_JMS( R, V );
end

% Plot intensities
figure(11)
plot(R6,I,'LineWidth',2)
legend([repmat('j = ',6,1),num2str((1:6)')])
xlabel('R_6 (Ohm)')
ylabel('I_j (Amp)')
grid on
set(gca,'FontSize',15)

% Plot power at resistances
figure(12)
plot(R6,PR,'LineWidth',2)
legend([repmat('j = ',6,1),num2str((1:6)')])
xlabel('R_6 (Ohm)')
ylabel('PR_j (Watt)')
grid on
set(gca,'FontSize',15)

% Plot power at sources
figure(13)
plot(R6,PV,'LineWidth',2)
legend([repmat('j = ',3,1),num2str((1:3)')])
xlabel('R_6 (Ohm)')
ylabel('PV_j (Watt)')
grid on
set(gca,'FontSize',15)

% Find R6 for which PV(3)=sum(PV)/2
DP = PV(3,:) - sum(PV)/2;
iR = find( DP(1:end-1) .* DP(2:end) < 0 );  % interval at which DP=0
R = (R6(iR)*DP(iR+1)-R6(iR+1)*DP(iR)) / (DP(iR+1)-DP(iR));  % lever rule
fprintf('PV_C=P_tot/2 at R6 = %6.4f Ohm\n',R)
