%Code for impedance matching on transmission lines
clear;
close all;
Z0 = 50; %char impedance
ZL = 75 + 1j * 100; %load impedance
lambda = 1; %wavelength in m
beta = 2*pi/lambda;

%% Complex load to Quarter wave transformer
%l = lambda/2;
%ZL_t = imp_transf(Z0,ZL,beta,l); %test

l = 0:lambda/100:lambda/2;
ZL_t = imp_transf(Z0,ZL,beta,l);
% figure; subplot(1,2,1);
% plot(l,real(ZL_t),'r'); grid; xlabel('l'); title('real part');
% subplot(1,2,2);
% plot(l,imag(ZL_t),'b'); grid; xlabel('l'); title('imag part');

%impedance matching for zero imag part
imp_imag = @(l) imag(imp_transf(Z0,ZL,beta,l));

L = fzero(imp_imag,0); %closest zero cross to 0
imp_transf(Z0,ZL,beta,L);

L = fzero(imp_imag,[0.2 0.4]);
imp_transf(Z0,ZL,beta,L);

%% Stub matching on a transmission line
%Part 1: Transform YL by some length L to YL_t s.t. real(YL_t)=Y0: gives L
%fn to calculate admittance as a fn of l
adm_transf = @(l) 1./imp_transf(Z0,ZL,beta,l);
Y0 = 1/Z0;
l = 0 : lambda/100 : lambda/2;
YL_t = adm_transf(l);
% figure;
% plot(l,real(YL_t)); grid;
% xlabel('l'); title('real(YL_t)');

stub_part1 = @(l) Y0 - real(adm_transf(l));
figure; 
plot(l,stub_part1(l)); grid;
xlabel('l'); title('Y0 - real(YL_t)');

% L = fzero(stub_part1,[0 lambda/4])
% YL_t = adm_transf(L);

L = fzero(stub_part1,[lambda/4,lambda/2])
YL_t = adm_transf(L)

%Part 2: Calculate Lsc s.t. imag(YL_t) = - imag(Y_sc_Lsc): Gives Lsc
%SC admittance as a fn of ls
adm_SC = @(ls) 1./(1j* Z0 * tan(beta*ls));
dl = lambda/100;
ls = 0 + dl : lambda/100 : lambda/2 - dl;
figure; plot(ls,imag(adm_SC(ls))); grid;
xlabel('ls'); title('imag(Y_sc)');

stub_part2 = @(ls) imag(YL_t) + imag(adm_SC(ls));
figure; plot(ls, stub_part2(ls)); grid;
xlabel('ls'); title('Net imag(Y)');

LS = fzero(stub_part2,[dl lambda/2-dl])


%impedance transformation
function [ZL_t] = imp_transf(Z0,ZL,beta,l)
%transform impedance by length l
%ZL_t = Z0 * (ZL + 1j* Z0 * tan(beta*l)) / (Z0 + 1j* ZL* tan(beta*l));
ZL_t = Z0 * (ZL * cos(beta*l) + 1j * Z0 * sin(beta*l)) ...
    ./ (Z0 * cos(beta*l) + 1j * ZL * sin(beta*l));
end