Here's a MATLAB script that extracts material properties from a Touchstone file containing free-space S-parameter measurements:
function [epsilon_r, mu_r, freq] = extract_material_properties(touchstone_file, thickness, varargin)
% EXTRACT_MATERIAL_PROPERTIES Extract complex permittivity and permeability from S-parameters
%
% Inputs:
% touchstone_file - Path to .s2p Touchstone file
% thickness - Sample thickness in meters
% varargin - Optional parameters as name-value pairs:
% 'magnetic' - true/false, whether to fit mu_r (default: false, assumes mu_r = 1)
% 'freq_range' - [f_min, f_max] in Hz to limit analysis range
% 'initial_guess' - [eps_r_real, eps_r_imag, mu_r_real, mu_r_imag] initial values
% 'plot_results' - true/false to plot results (default: true)
%
% Outputs:
% epsilon_r - Complex relative permittivity (Nx1 array)
% mu_r - Complex relative permeability (Nx1 array)
% freq - Frequency points (Nx1 array)
%
% Example:
% [eps, mu, f] = extract_material_properties('sample.s2p', 0.005, 'magnetic', false);
% Parse optional inputs
p = inputParser;
addParameter(p, 'magnetic', false, @islogical);
addParameter(p, 'freq_range', [], @(x) isnumeric(x) && length(x)==2);
addParameter(p, 'initial_guess', [5, 0.1, 1, 0], @(x) isnumeric(x) && length(x)==4);
addParameter(p, 'plot_results', true, @islogical);
parse(p, varargin{:});
opts = p.Results;
% Physical constants
c0 = 299792458; % Speed of light in vacuum (m/s)
eta0 = 376.730313668; % Free space impedance (ohms)
% Read Touchstone file
fprintf('Reading Touchstone file: %s\n', touchstone_file);
[S_params, freq] = read_touchstone(touchstone_file);
% Apply frequency range if specified
if ~isempty(opts.freq_range)
idx = freq >= opts.freq_range(1) & freq <= opts.freq_range(2);
freq = freq(idx);
S_params = S_params(idx, :, :);
end
% Extract S11 and S21
S11_meas = squeeze(S_params(:, 1, 1));
S21_meas = squeeze(S_params(:, 2, 1));
% Initialize output arrays
N = length(freq);
epsilon_r = zeros(N, 1);
mu_r = ones(N, 1);
% Optimization options
opt_options = optimoptions('lsqnonlin', ...
'Display', 'iter-detailed', ...
'TolFun', 1e-8, ...
'TolX', 1e-8, ...
'MaxIterations', 500, ...
'Algorithm', 'levenberg-marquardt');
% Fit material properties at each frequency
fprintf('\nExtracting material properties...\n');
for i = 1:N
if mod(i, 10) == 0 || i == 1 || i == N
fprintf('Processing frequency %d/%d (%.2f GHz)\n', i, N, freq(i)/1e9);
end
% Define objective function for this frequency
obj_func = @(x) objective_function(x, S11_meas(i), S21_meas(i), ...
freq(i), thickness, opts.magnetic);
% Set bounds
if opts.magnetic
% [eps_r_real, eps_r_imag, mu_r_real, mu_r_imag]
lb = [1, -10, 1, -10];
ub = [100, 0, 100, 0];
x0 = opts.initial_guess;
else
% [eps_r_real, eps_r_imag] only
lb = [1, -10];
ub = [100, 0];
x0 = opts.initial_guess(1:2);
end
% Run optimization
[x_opt, ~] = lsqnonlin(obj_func, x0, lb, ub, opt_options);
% Extract results
epsilon_r(i) = x_opt(1) + 1j*x_opt(2);
if opts.magnetic
mu_r(i) = x_opt(3) + 1j*x_opt(4);
end
% Use current solution as initial guess for next frequency
if opts.magnetic
opts.initial_guess = x_opt;
else
opts.initial_guess(1:2) = x_opt;
end
end
% Plot results if requested
if opts.plot_results
plot_results(freq, epsilon_r, mu_r, S11_meas, S21_meas, thickness, opts.magnetic);
end
end
%% Helper Functions
function [S_params, freq] = read_touchstone(filename)
% READ_TOUCHSTONE Read S-parameters from Touchstone file
fid = fopen(filename, 'r');
if fid == -1
error('Cannot open file: %s', filename);
end
% Skip header lines and find option line
freq_scale = 1e9; % Default GHz
while ~feof(fid)
line = fgetl(fid);
if startsWith(line, '#')
% Parse option line
tokens = strsplit(upper(line));
for j = 1:length(tokens)
switch tokens{j}
case 'HZ'
freq_scale = 1;
case 'KHZ'
freq_scale = 1e3;
case 'MHZ'
freq_scale = 1e6;
case 'GHZ'
freq_scale = 1e9;
end
end
break;
end
end
% Read data
data = [];
while ~feof(fid)
line = fgetl(fid);
if ischar(line) && ~startsWith(line, '!') && ~isempty(strtrim(line))
values = sscanf(line, '%f');
if ~isempty(values)
data = [data; values'];
end
end
end
fclose(fid);
% Parse data (assuming RI format: freq, Re(S11), Im(S11), Re(S21), Im(S21), Re(S12), Im(S12), Re(S22), Im(S22))
freq = data(:, 1) * freq_scale;
N = length(freq);
S_params = zeros(N, 2, 2);
S_params(:, 1, 1) = data(:, 2) + 1j*data(:, 3); % S11
S_params(:, 2, 1) = data(:, 4) + 1j*data(:, 5); % S21
S_params(:, 1, 2) = data(:, 6) + 1j*data(:, 7); % S12
S_params(:, 2, 2) = data(:, 8) + 1j*data(:, 9); % S22
end
function residual = objective_function(x, S11_meas, S21_meas, freq, thickness, fit_magnetic)
% OBJECTIVE_FUNCTION Calculate residual between measured and calculated S-parameters
% Extract parameters
eps_r = x(1) + 1j*x(2);
if fit_magnetic
mu_r = x(3) + 1j*x(4);
else
mu_r = 1;
end
% Calculate theoretical S-parameters
[S11_calc, S21_calc] = calculate_s_params(eps_r, mu_r, freq, thickness);
% Compute residual (real and imaginary parts separately)
residual = [
real(S11_meas - S11_calc);
imag(S11_meas - S11_calc);
real(S21_meas - S21_calc);
imag(S21_meas - S21_calc)
];
end
function [S11, S21] = calculate_s_params(eps_r, mu_r, freq, thickness)
% CALCULATE_S_PARAMS Calculate theoretical S-parameters for a material slab
% Constants
c0 = 299792458;
eta0 = 376.730313668;
% Calculate material parameters
n = sqrt(eps_r * mu_r); % Refractive index
eta = eta0 * sqrt(mu_r / eps_r); % Material impedance
% Wave parameters
omega = 2 * pi * freq;
k0 = omega / c0; % Free space wave number
k = k0 * n; % Wave number in material
% Propagation through material
gamma_d = 1j * k * thickness;
% Reflection coefficient at interface
Gamma = (eta - eta0) / (eta + eta0);
% Transmission coefficient at interface
T = 2 * eta / (eta + eta0);
T_rev = 2 * eta0 / (eta + eta0);
% Multiple reflection factor
exp_2gamma = exp(-2 * gamma_d);
denom = 1 - Gamma^2 * exp_2gamma;
% S-parameters
S11 = Gamma * (1 - exp_2gamma) / denom;
S21 = T * T_rev * exp(-gamma_d) / denom;
end
function plot_results(freq, epsilon_r, mu_r, S11_meas, S21_meas, thickness, magnetic)
% PLOT_RESULTS Plot extracted material properties and S-parameter fit
% Calculate fitted S-parameters
N = length(freq);
S11_fit = zeros(N, 1);
S21_fit = zeros(N, 1);
for i = 1:N
[S11_fit(i), S21_fit(i)] = calculate_s_params(epsilon_r(i), mu_r(i), freq(i), thickness);
end
figure('Position', [100, 100, 1200, 800]);
% Plot permittivity
subplot(2, 3, 1);
plot(freq/1e9, real(epsilon_r), 'b-', 'LineWidth', 2);
hold on;
plot(freq/1e9, -imag(epsilon_r), 'r-', 'LineWidth', 2);
xlabel('Frequency (GHz)');
ylabel('\epsilon_r');
title('Relative Permittivity');
legend('\epsilon_r''', '\epsilon_r''''', 'Location', 'best');
grid on;
% Plot permeability if magnetic
if magnetic
subplot(2, 3, 2);
plot(freq/1e9, real(mu_r), 'b-', 'LineWidth', 2);
hold on;
plot(freq/1e9, -imag(mu_r), 'r-', 'LineWidth', 2);
xlabel('Frequency (GHz)');
ylabel('\mu_r');
title('Relative Permeability');
legend('\mu_r''', '\mu_r''''', 'Location', 'best');
grid on;
end
% Plot loss tangent
subplot(2, 3, 3);
tan_delta = -imag(epsilon_r) ./ real(epsilon_r);
plot(freq/1e9, tan_delta, 'k-', 'LineWidth', 2);
xlabel('Frequency (GHz)');
ylabel('tan \delta');
title('Loss Tangent');
grid on;
% Plot S11 comparison
subplot(2, 3, 4);
plot(freq/1e9, 20*log10(abs(S11_meas)), 'ko', 'MarkerSize', 4);
hold on;
plot(freq/1e9, 20*log10(abs(S11_fit)), 'r-', 'LineWidth', 2);
xlabel('Frequency (GHz)');
ylabel('|S_{11}| (dB)');
title('S_{11} Magnitude');
legend('Measured', 'Fitted', 'Location', 'best');
grid on;
% Plot S21 comparison
subplot(2, 3, 5);
plot(freq/1e9, 20*log10(abs(S21_meas)), 'ko', 'MarkerSize', 4);
hold on;
plot(freq/1e9, 20*log10(abs(S21_fit)), 'r-', 'LineWidth', 2);
xlabel('Frequency (GHz)');
ylabel('|S_{21}| (dB)');
title('S_{21} Magnitude');
legend('Measured', 'Fitted', 'Location', 'best');
grid on;
% Plot phase comparison
subplot(2, 3, 6);
plot(freq/1e9, angle(S21_meas)*180/pi, 'ko', 'MarkerSize', 4);
hold on;
plot(freq/1e9, angle(S21_fit)*180/pi, 'r-', 'LineWidth', 2);
xlabel('Frequency (GHz)');
ylabel('Phase of S_{21} (degrees)');
title('S_{21} Phase');
legend('Measured', 'Fitted', 'Location', 'best');
grid on;
sgtitle(sprintf('Material Property Extraction (d = %.1f mm)', thickness*1000));
end
Usage Example:
% Basic usage for non-magnetic material
[eps, mu, f] = extract_material_properties('sample_measurement.s2p', 0.005);
% For magnetic material
[eps, mu, f] = extract_material_properties('ferrite_sample.s2p', 0.003, ...
'magnetic', true, ...
'initial_guess', [10, 0.5, 2, 0.1]);
% Limit frequency range
[eps, mu, f] = extract_material_properties('sample.s2p', 0.005, ...
'freq_range', [1e9, 10e9]);
Key Features:
-
Robust Optimization: Uses Levenberg-Marquardt algorithm to fit S-parameters across the entire frequency range, avoiding single-frequency inversion issues.
-
Frequency-by-Frequency Fitting: Extracts frequency-dependent material properties without assuming a specific dispersion model.
-
Smart Initialization: Uses the solution from the previous frequency as the initial guess for the next, improving convergence.
-
Flexible Options:
- Can fit both permittivity and permeability or just permittivity
- Allows specification of frequency range
- Customizable initial guesses
-
Comprehensive Visualization: Plots extracted properties and compares measured vs. fitted S-parameters to validate results.
-
Touchstone File Support: Reads standard .s2p files with automatic frequency scaling detection.
Important Notes:
- The script assumes the Touchstone file is in RI (Real-Imaginary) format. Modify the
read_touchstone function if your files use MA (Magnitude-Angle) or DB (dB-Angle) format.
- For best results with magnetic materials, good initial guesses are important.
- The optimization bounds can be adjusted based on expected material properties.
- Consider using multiple sample thicknesses and combining the data for more robust extraction, especially near λ/4 resonances.