%
% Convert S-matrix to Z-matrix
% MATLAB
% 2021/9/13 By Takuichi Hirano
%
% [Input file format (s_para.csv)]
%    frequency, s11(dB), s11(deg), s12(dB), s12(deg), ...
%               s21(dB), s21(deg), s22(dB), s22(deg)
% [Output file format (z_para.csv)]
%    frequency, z11(real), z11(imag), z12(real), z12(imag), ...
%               s21(real), s21(imag), s22(real), s22(imag)
%

%% Input File
fS = readmatrix('s_para.csv');
%% Import Data for Processing
nfreq = length(fS);
freq=zeros(nfreq,1);
z0 = 50;    % Port Reference Impedance
fZ = zeros(nfreq,9);
for i=1:nfreq
    freq(i)=fS(i,1);
    S11=10^(fS(i,2)/20)*exp(1i*fS(i,3)*(pi/180));
    S12=10^(fS(i,4)/20)*exp(1i*fS(i,5)*(pi/180));
    S21=10^(fS(i,6)/20)*exp(1i*fS(i,7)*(pi/180));
    S22=10^(fS(i,8)/20)*exp(1i*fS(i,9)*(pi/180));
    S=[S11 S12; S21 S22];
    Z=TransS2Z(S,[z0 z0]);
    fZ(i,:)=[freq(i) real(Z(1,1)) imag(Z(1,1)) real(Z(1,2)) imag(Z(1,2)) ...
                   real(Z(2,1)) imag(Z(2,1)) real(Z(2,2)) imag(Z(2,2))];
end
writematrix(fZ,'z_para.csv');

%% Definitions of Functions
% S -> Z
% [Example]
%    S = [1 2; 3 4] % S-matrix
%    z0 = [10 11]   % Port reference impedances
function Z = TransS2Z(S,z0)
    I = eye(length(S));
    U = diag(sqrt(z0));
    Z = U*(I+S)*inv(I-S)*U;
end

% Z -> S
% [Example]
%    Z = [1 2; 3 4] % Z-matrix
%    z0 = [10 11]   % Port reference impedances
function S = TransZ2S(Z,z0)
    I = eye(length(Z));
    V = diag(1./sqrt(z0));
    Z2 = V*Z*V;
    S = (Z2-I)*inv(Z2+I);
end