Generated banner for Matlab Optimize Pcb Design
Generated logo for Matlab Optimize Pcb Design

Matlab Optimize Pcb Design

MathWorksOfficialCreated by MathWorks

  • Skill
  • Tool integration
  • Software development
  • BSD-2-Clause
  • No issues found

From the author

Optimize RF PCB dimensions for bandwidth, return loss, or area via patternsearch and surrogateopt with constraints. TRIGGER: user asks to optimize an RF PCB component for performance (bandwidth, return loss, insertion loss, area) or apply constraints to a design. Invoke BEFORE writing optimization code — RF PCB Toolbox has a built-in optimize() function that differs from generic fmincon/ga approaches. SKIP: designing a component from scratch without an optimization objective (use the specific matlab-design-pcb-* skill), EM analysis without optimization (use matlab-analyze-em), material/stackup setup only (use matlab-manage-pcb-material).
— the description by MathWorks

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow for optimizing RF PCB component dimensions using the RF PCB Toolbox. It emphasizes the use of the built-in optimize function, which supports various solvers like patternsearch, surrogateopt, SADEA, and TR-SADEA. The guide covers defining objective functions, setting geometric bounds, applying S-parameter constraints, and validating results, while warning against manual optimization loops that bypass the toolbox's native capabilities.

What it does

  • Provides a standardized workflow for tuning RF PCB dimensions for performance.
  • Wraps multiple optimization solvers including SADEA, TR-SADEA, patternsearch, and surrogateopt.
  • Supports optimization for bandwidth, return loss, insertion loss, and board area.
  • Enables the application of S-parameter constraints to ensure design feasibility.
  • Offers guidance on selecting the appropriate solver based on model complexity and computational cost.
  • Includes patterns for post-optimization validation and metric extraction.

When to use it

  • When you need to tune filter, coupler, or splitter dimensions for specific performance targets.
  • When you have an initial design created via design functions and need to refine its parameters.
  • When you need to minimize board area or maximize return loss within defined geometric bounds.
  • When you require an automated approach to satisfy S-parameter constraints across a frequency band.

Advantages

  • Prevents brittle code by discouraging manual optimization loops.
  • Leverages built-in, optimized solvers specifically tuned for RF PCB Toolbox objects.
  • Provides a consistent interface for both simple and complex optimization tasks.
  • Supports efficient surrogate-based optimization for computationally expensive EM models.

Usage examples

“Optimize the dimensions of a Wilkinson splitter to minimize board area while keeping S11 below -10 dB.”
The agent will define the splitter object, set property bounds, define the S11 constraint, and execute the optimize function using the patternsearch solver.
“How do I maximize the return loss of a hairpin filter using surrogate optimization?”
The agent will guide you to set up the hairpin filter, define the property bounds, and call the optimize function with the surrogateopt solver and specified optimizer options.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/matlab/matlab-optimize-pcb-design/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip matlab-optimize-pcb-design.zip -d .agents/skills

Documentation by MathWorks

Optimizing RF PCB Designs

Critical: Always Use optimize() First

The RF PCB Toolbox provides a built-in optimize() function that handles all standard optimization scenarios. Always use it as the first approach — do NOT write manual optimization loops with patternsearch, surrogateopt, fmincon, or ga called directly unless optimize() is demonstrably insufficient for the specific problem.

When to Use

  • Tuning filter, coupler, or splitter dimensions for return loss, bandwidth, or area

  • Running optimize() on catalog objects with bounds and constraints

  • Using SADEA/TR-SADEA, patternsearch, or surrogateopt via the optimize() interface

  • Defining custom objective functions over S-parameter responses

When NOT to Use

  • Designing components from scratch — use matlab-design-pcb-filter, matlab-design-pcb-coupler, etc. first, then optimize

  • Running EM analysis without optimization — use matlab-analyze-em

  • Parameter sweeps without an objective — just loop over sparameters calls directly

  • Antenna-only optimization without PCB context — use Antenna Toolbox docs

Typical Workflow

  1. Before: A design skill (matlab-design-pcb-filter, matlab-design-pcb-transmission-line, etc.) — create the initial component; matlab-analyze-em — baseline S-parameters

  2. This skill: Define objective, bounds, constraints; run optimize()

  3. After: matlab-analyze-em — validate optimized design → matlab-integrate-pcb-circuit — cascade into system → matlab-write-pcb-layout — export Gerber

Quick Reference

TaskCode
Design at frequencyobj = design(ObjectType, fc)
OptimizeoptObj = optimize(obj, freq, objective, props, bounds, solver)
With constraintsoptimize(..., 'Constraints', constraints)
With optionsoptimize(..., 'OptimizerOptions', opts)

Algorithm Overview

AlgorithmSourceBest ForTypical Time
sadeaAntenna Toolbox (SADEA)Default global search, few EM evaluations5--30 min
trsadeaAntenna Toolbox (TR-SADEA)Trust-region variant, better local refinement5--30 min
patternsearchGlobal Optimization ToolboxDerivative-free, smooth/noisy EM objectives, fine-tuning2--15 min
surrogateoptGlobal Optimization ToolboxExpensive black-box functions, many variables, global optimum10--60 min
  • Start with SADEA -- it requires no additional toolbox beyond Antenna Toolbox and handles most RF/PCB optimization problems well.

  • Use patternsearch for fine-tuning -- after SADEA finds a good region, refine with patternsearch starting from the SADEA result.

  • surrogateopt for expensive models -- builds a surrogate model and is more sample-efficient when each EM solve is costly.

Timing and Practical Considerations

  • MoM simulation per evaluation: 2--30 seconds for simple components, minutes for high-order filters

  • Behavioral mode: Use pcbElement(comp, Behavioral=true) for fast analytical evaluations during optimization sweeps

  • Iteration budget: Set MaxIterations to 20--50 when running interactively to stay responsive; use 100--200 for batch runs

  • Parallel computing: Set UseParallel=true if Parallel Computing Toolbox is available for significant speedup with patternsearch and surrogateopt

design() — Initial Sizing

The design function sizes any catalog component for a target frequency:

ws = design(wilkinsonSplitter, 3e9);
bl = design(couplerBranchline, 5e9);
fh = design(filterHairpin, 2.4e9);
ms = design(microstripLine, 3e9);

This produces a starting point for subsequent optimization. All geometric parameters are auto-computed for the target frequency.

optimize() Syntax

optObj = optimize(obj, freq, objective, properties, bounds, solver, ...
    'Constraints', constraints, 'OptimizerOptions', opts)
ArgumentTypeDescription
objObjectCatalog object (initial design)
freqScalar or vectorSingle frequency or frequency vector for optimization
objectiveStringBuilt-in or custom objective function name
propertiesCell arrayProperty names to vary
bounds2-element cell{[lower1 lower2 ...]; [upper1 upper2 ...]}
solverString'patternsearch', 'surrogateopt', 'sadea', or 'trsadea'
constraintsStructS-parameter constraints (optional NV pair)
optsoptimoptionsOptimizer options object created with optimoptions()

Built-in Objectives

Objective StringMinimizes/Maximizes
"minimizeArea"Minimizes board area
"maximizeBandwidth"Maximizes -10 dB return loss bandwidth
"maximizeReturnLoss"Maximizes worst-case return loss
"minimizeBandwidth"Narrows the passband

Example: Minimize Area with Constraints

obj = design(wilkinsonSplitter, 3e9);

props = {'SplitLineLength', 'SplitLineWidth', 'Resistance', ...
         'PortLineLength', 'GroundPlaneWidth'};
bounds = {[10e-3 1e-3  50 2e-3  10e-3];    % Lower bounds
          [50e-3 8e-3 100 20e-3 50e-3]};    % Upper bounds (cell array!)

constraints.S11 = '<-10';
constraints.S21 = '>-4';
constraints.S22 = '<-10';
constraints.S12 = '>-4';

optObj = optimize(obj, 3e9, "minimizeArea", props, bounds, ...
    "patternsearch", 'Constraints', constraints);

show(optObj);
sp = sparameters(optObj, linspace(1e9, 5e9, 51), 'SweepOption', 'interp');
rfplot(sp);

% Verify area from shapes
s = shapes(optObj);           % Returns struct of shapes by layer
boardArea = area(s.GroundPlane);
fprintf('Optimized board area: %.2f mm²\n', boardArea * 1e6);
Querying Area After Optimization

For catalog objects, use shapes() to extract the individual layer shapes, then area():

s = shapes(optObj);              % Catalog object → struct with named shapes
boardArea = area(s.GroundPlane); % Area of the board outline shape

For pcbComponent, shapes are in the Layers property:

pcb = pcbComponent(optObj);
boardArea = area(pcb.BoardShape);

Example: Maximize Return Loss for Hairpin Filter

f = design(filterHairpin, 3e9);

props = {'CoupledLineLength', 'CoupledLineWidth', 'CoupledLineSpacing'};
bounds = {[5e-3 0.5e-3 0.1e-3];
          [40e-3 5e-3 2e-3]};

optF = optimize(f, 3e9, "maximizeReturnLoss", props, bounds, "patternsearch");
show(optF);

S-Parameter Constraints

Constraints use string format '<threshold' or '>threshold' (in dB):

constraints.S11 = '<-15';    % S11 below -15 dB
constraints.S21 = '>-1';     % S21 above -1 dB (low insertion loss)
constraints.S31 = '<-20';    % Isolation below -20 dB

Any S-parameter index can be constrained. The optimizer evaluates constraints across the entire frequency vector.

Custom Objective Functions

For objectives beyond the built-in set, provide a function handle:

% Objective function signature: cost = objFcn(obj, freq)
function cost = myObjective(obj, freq)
    sp = sparameters(obj, freq, 'SweepOption', 'interp');
    S21 = squeeze(sp.Parameters(2,1,:));
    S11 = squeeze(sp.Parameters(1,1,:));
    % Minimize worst-case insertion loss while maintaining match
    cost = -min(20*log10(abs(S21)));  % Negative because we maximize |S21|
end

optObj = optimize(obj, fc, @myObjective, props, bounds, "patternsearch");

Surrogate-Based Optimization

For expensive EM solves, surrogate optimization builds a model and is more sample-efficient:

opts = optimoptions('surrogateopt', 'MaxFunctionEvaluations', 50);
optObj = optimize(obj, 3e9, "maximizeReturnLoss", props, bounds, ...
    "surrogateopt", 'OptimizerOptions', opts);

Solver Options

The OptimizerOptions NV pair takes an optimoptions object for the chosen solver:

opts = optimoptions('patternsearch', 'MaxFunctionEvaluations', 100, 'Display', 'off');
optObj = optimize(obj, fc, objective, props, bounds, 'patternsearch', ...
    'OptimizerOptions', opts);

Available solvers: 'patternsearch', 'surrogateopt', 'sadea', 'trsadea'.

For sadea/trsadea, pass a struct instead of an optimoptions object:

opts = struct('MaxIterations', 50, 'UseParallel', false);
optObj = optimize(obj, fc, objective, props, bounds, 'sadea', ...
    'OptimizerOptions', opts);

Nested Property Optimization

Optimize nested properties using dot notation:

% Optimize substrate thickness along with width
optObj = optimize(ml, 2.4e9, 'maximizeReturnLoss', ...
    {'Width', 'Substrate.Thickness'}, ...
    {0.001 0.5e-3; 0.01 3e-3}, 'sadea');

Decision: optimize() vs Manual Loop

Always use optimize(). It wraps all four solvers (sadea, trsadea, patternsearch, surrogateopt) internally. There is no performance or capability advantage to calling these solvers directly. The only scenario where direct solver usage is justified is a non-S-parameter, non-EM objective function that optimize() cannot express (extremely rare).

Optimization Workflow

  1. Design initial geometry: obj = design(Type, fc)

  2. Select properties to vary: Choose 3-6 most impactful dimensions

  3. Set reasonable bounds: ±50% of initial values is a good starting range

  4. Define constraints: Ensure feasibility (S11 < -10 dB at minimum)

  5. Choose solver: Start with 'sadea'; use 'patternsearch' for refinement

  6. Run optimize(): optObj = optimize(obj, freq, objective, props, bounds, solver)

  7. Validate: Check optimized design meets specs across full band

Antenna Objects with optimize()

The same optimize() function works on antenna objects with antenna-specific objectives:

ObjectiveDescription
'maximizeGain'Maximize antenna gain at target frequency
'frontToBackRatio'Maximize front-to-back lobe ratio
'maximizeSLL'Maximize sidelobe level suppression
ant = design(patchMicrostrip, 2.4e9);
optAnt = optimize(ant, 2.4e9, 'maximizeGain', ...
    {'Length', 'Width'}, {[0.02 0.02]; [0.06 0.06]}, 'sadea', ...
    'OptimizerOptions', struct('MaxIterations', 100));
pattern(optAnt, 2.4e9);

These objectives are for antenna objects only. RF PCB catalog objects use the objectives in the Built-in Objectives table above.

Fallback: Direct Solver Usage (Last Resort)

Direct solver calls are almost never needed — optimize() already wraps patternsearch, surrogateopt, sadea, and trsadea. Only bypass optimize() for non-EM objectives it cannot express (e.g., multi-objective Pareto front via paretosearch).

% Extremely rare: multi-objective Pareto (not supported by optimize())
objFcn = @(x) [emObjective(obj, x, freq); thermalObjective(obj, x)];
[xopt, fval] = paretosearch(objFcn, nVars, [], [], [], [], lb, ub);

Design Iteration Patterns

Variable Naming Conventions

Use these names consistently across optimization scripts and iterative design loops:

sub    % dielectric substrate
cond   % metal conductor
ml     % microstripLine
sl     % stripLine
cpw    % coplanarWaveguide
cm     % coupledMicrostripLine
filt   % any filter object
coup   % any coupler object
split  % any splitter object
comp   % pcbComponent
sp     % sparameters result
freq   % frequency vector
Metric Extraction Patterns

Always extract numerical summaries after analysis -- tools like Amp cannot interpret MATLAB figures.

sp = sparameters(comp, freq, 'SweepOption', 'interp');
S = sp.Parameters;
s21_dB = 20*log10(abs(squeeze(S(2,1,:))));
s11_dB = 20*log10(abs(squeeze(S(1,1,:))));
freq_GHz = sp.Frequencies/1e9;

% Key metrics
insertionLoss = max(s21_dB);
returnLoss = min(s11_dB);
[~, idx] = max(s21_dB);
centerFreq = freq_GHz(idx);

% 3 dB bandwidth
aboveCutoff = find(s21_dB >= max(s21_dB) - 3);
bw3dB = NaN;
if ~isempty(aboveCutoff)
    bw3dB = (freq_GHz(aboveCutoff(end)) - freq_GHz(aboveCutoff(1))) * 1e3;
end

fprintf('Center: %.3f GHz | IL: %.2f dB | RL: %.2f dB | BW: %.0f MHz\n', ...
    centerFreq, insertionLoss, returnLoss, bw3dB);
Before/After Comparison Workflow
% 1. Save baseline metrics before adjusting
oldIL = insertionLoss;
oldBW = bw3dB;

% 2. Adjust property (or run optimize)
filt.FilterOrder = 5;  % was 3

% 3. Re-analyze and extract new metrics
sp_new = sparameters(filt, freq, 'SweepOption', 'interp');
s21_new = 20*log10(abs(squeeze(sp_new.Parameters(2,1,:))));
newIL = max(s21_new);
aboveCutoff = find(s21_new >= max(s21_new) - 3);
newBW = (freq_GHz(aboveCutoff(end)) - freq_GHz(aboveCutoff(1))) * 1e3;

% 4. Compare
fprintf('Before: IL=%.2f dB, BW=%.0f MHz\n', oldIL, oldBW);
fprintf('After:  IL=%.2f dB, BW=%.0f MHz\n', newIL, newBW);
Design Adjustment Guide
ProblemProperty to AdjustDirection
Passband too wideFilterOrder / SpacingIncrease order / decrease spacing
Passband too narrowSpacingIncrease
Insertion loss too highConductor thickness / FilterOrderUse real metal / reduce order
Center freq shiftedRe-run design(filt, newFreq)--
Z0 too highWidthIncrease
Z0 too lowWidthDecrease
Coupling too tightSpacingIncrease
Coupling too looseSpacingDecrease

Pitfalls

  1. Do NOT write manual optimization loops. Never call patternsearch, surrogateopt, fmincon, or ga directly with a hand-written objective function wrapping sparameters. The built-in optimize() already wraps these solvers and handles property assignment, bounds checking, and S-parameter evaluation internally. Writing a manual loop duplicates this logic incorrectly and produces brittle code.

  2. EM solve cost: Each optimization iteration requires a full EM solve. Use interpolating sweep for faster convergence.

  3. Bound width: Too-wide bounds increase search space exponentially. Start with ±30-50% of initial values and narrow after first pass.

  4. Initial feasibility: If the initial design violates constraints, the optimizer may struggle. Always start from a design()-generated initial point.

  5. Property dependencies: Some properties are coupled (e.g., ArmLength and PortLineLength overlap spatially). Choose independent properties to avoid infeasible geometries.

  6. Convergence check: Pattern search may stall at local minima. Run multiple times with different initial meshes or use surrogateopt for global exploration.

  7. Requires toolbox licenses: patternsearch and surrogateopt require Global Optimization Toolbox. sadea and trsadea require Antenna Toolbox.

  8. Frequency can be scalar or vector: optimize accepts both a single frequency and a frequency vector. Vectors evaluate the objective across the band but increase solve time per iteration.

  9. Bounds are a cell array: Pass bounds as {[lb1 lb2 ...]; [ub1 ub2 ...]}, not a numeric matrix. Each cell element is a row vector.

  10. OptimizerOptions format depends on solver: For patternsearch/surrogateopt, pass optimoptions('patternsearch', ...). For sadea/trsadea, pass a struct: struct('MaxIterations', 50, 'UseParallel', false).

  11. Vector properties expand bounds count. After design(), some properties become vectors (e.g., filterCoupledLine.CoupledLineLength is a 4-element vector for a 4-section filter). Bounds must match the total scalar count across all properties. If you optimize {'CoupledLineLength','CoupledLineSpacing'} and each is a 4-element vector, bounds need 8 lower and 8 upper values — not 2. Check numel(obj.PropertyName) before setting bounds.

  12. Interp sweep requires ≥2 frequencies. sparameters(obj, scalarFreq, 'SweepOption', 'interp') errors — the interpolating solver needs at least 2 frequency points. When validating baseline S-parameters outside of optimize(), use a frequency vector: sparameters(obj, linspace(f1, f2, N), 'SweepOption', 'interp').

  13. Variables at bounds suggest wider search. If an optimized property converges to exactly the lower or upper bound, the true optimum may lie outside the search region. Re-run with widened bounds in that direction.

  14. Constraint tolerance. The optimizer may accept solutions that violate constraints by a small margin (~0.3 dB). If strict compliance is required, tighten constraints slightly (e.g., use '<-10.5' when the spec is -10 dB).

  • matlab-design-pcb-filter — Filter objects to optimize

  • matlab-design-pcb-coupler — Coupler/splitter objects to optimize

  • matlab-analyze-em — Understanding S-parameter results


Copyright 2026 The MathWorks, Inc.

Files

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
MathWorks
Publisher
MathWorks (Official)
Source
matlab/matlab-agentic-toolkit · skills-catalog/rf-and-mixed-signal/matlab-optimize-pcb-design · commit 2a7f215
Licence
BSD 2-Clause License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by MathWorks.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-optimize-pcb-design.zip