Generated banner for Matlab Model Optics
Generated logo for Matlab Model Optics

Matlab Model Optics

MathWorksOfficialCreated by MathWorks

  • Skill
  • Tool integration
  • Science and research
  • BSD-2-Clause
  • No issues found

From the author

Build, import, analyze, tolerate, and optimize optical systems using the Optical Design and Simulation Library. Use when the user asks about optical systems, ray tracing, geometric optics, Zemax import, optical coatings, tolerancing, or optical design optimization.
— the description by MathWorks

AutoGineer summary

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

The matlab-model-optics skill provides an interface for the Optical Design and Simulation Library in MATLAB. It enables users to construct, import, and simulate optical systems, including ray tracing, paraxial analysis, and thin-film coating design. The skill supports importing Zemax files, performing tolerancing, and optimizing optical designs, as well as integrating dynamic optical models into Simulink.

What it does

  • Constructs optical systems using refractive surfaces, mirrors, and diaphragms.
  • Imports and converts existing Zemax (.zmx) optical designs.
  • Performs geometric optics analysis including ray tracing, spot diagrams, and aberration calculations.
  • Designs and optimizes thin-film optical coatings with spectral performance goals.
  • Conducts tolerancing and sensitivity analysis for manufacturing feasibility.
  • Integrates optical models into Simulink for dynamic system simulation.

When to use it

  • When designing or analyzing sequential optical systems.
  • When you need to import and evaluate existing Zemax optical prescriptions.
  • When optimizing lens parameters or thin-film coating thicknesses.
  • When performing sensitivity or Monte Carlo yield analysis on optical designs.
  • When modeling dynamic optical components within a Simulink control loop.

Advantages

  • Seamless integration with MATLAB's numerical optimization and visualization tools.
  • Supports complex multi-layer coating design and spectral response analysis.
  • Enables automated tolerancing workflows to predict manufacturing yield.
  • Provides a programmatic approach to optical system construction and modification.

Usage examples

“How do I import a Cooke triplet from a Zemax file?”
The agent will guide you to use the zmximport function and explain how to manage components and gaps after the import.
“Help me optimize an anti-reflection coating for the visible spectrum.”
The agent will provide a template for defining coating materials, layer structures, and spectral merit functions to use with a bounded optimizer.
“How can I model a scanning mirror in Simulink?”
The agent will explain how to use a MATLAB Function block with an extrinsic optics function to update mirror tilt angles at each simulation timestep.
“Show me how to calculate the spot diagram for a custom lens system.”
The agent will provide code to define the optical system, set field points, run the spot analysis, and visualize the results using spotDiagram.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/matlab/matlab-model-optics/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip matlab-model-optics.zip -d .agents/skills

Documentation by MathWorks

Optical Design and Simulation Library

Use this skill when the user is working with the Optical Design and Simulation Library to build, import, analyze, tolerate, or optimize optical systems in MATLAB.

This library may also be referred to as:

  • Optical Design and Simulation Library

  • Optics Support Package

  • Optics Add-On

  • Optics Library

  • Optics Toolbox

Use Optical Design and Simulation Library as the canonical name in responses unless the user explicitly uses a different name.

When to Use

Use this skill when the user asks about:

  • Optical Systems

  • Ray Tracing

  • Geometric Optics based analysis like lens distortion, spot diagrams, chromatic aberration, astigmatism and ray fans

  • Paraxial Optics

  • Optical Coatings

  • Polarization or EM analysis (computing Fresnel Coefficients)

  • Glass Materials and Glass Catalogs

  • Zemax import

  • Optical Tolerancing

  • Optical System Design and Optimization

  • Dynamic optical systems in Simulink (see references/dynamic-optical-systems-simulink.md)

When NOT to Use

Do not use this skill when:

  • The user is working with physical optics or wave optics (diffraction, interference, coherence)

  • The user is working with fiber optics or photonics

  • The user needs image processing or computer vision (use Image Processing Toolbox instead)

  • The task is purely about Simulink modeling without optical system involvement

First Steps

When helping a user who is new to the library, start with discovery:

help optics

To get more details for a specific function:

help lensDistortion
doc lensDistortion

Many optics APIs are class methods. For class methods, use:

help className/functionName
doc className/functionName

Example:

help opticalSystem/add

Use examples in the documentation when the user asks for a larger end-to-end workflow.

Sample ZMX Files

The Optical Design and Simulation Library ships sample Zemax (.zmx) files in the opticsdata folder within the support package install location. To find the path:

spkgRoot = fullfile(matlabshared.supportpkg.getSupportPackageRoot, "toolbox", "images", "supportpackages", "opticsdata");
dir(fullfile(spkgRoot, "*.zmx"))

When a user asks to work with a standard optical system (e.g., "a Cooke triplet", "a doublet", "a telephoto lens") but does not provide their own file:

  1. List the available .zmx files in the opticsdata folder

  2. Pick the sample system that best matches the user's request

  3. Import it using zmximport

This avoids asking the user for a file path when a suitable sample already exists.

Core Concepts

opticalSystem

opticalSystem is the central object representing a physical optical system.

opsys = opticalSystem(Wavelengths=[486.134 587.562 656.281]);
opticalMaterial

opticalMaterial represents a glass or optical material.

mat = opticalMaterial([1.5168 64.17]);
mat = pickGlass("N-BK7");
opticalCoating

opticalCoating represents a thin-film coating applied to surfaces.

oc = opticalCoating(CoatingMaterial=["MgF2" "TiO2"], LayerMaterialIndex=[1 2 1 2], LayerThickness=[1 0.5 1 0.5], PrimaryWavelength=550);
oc = pickCoating("AR_MgF2_VIS");
addCoating(opsys, oc);
addCoating(opsys, oc, CoatingSide="front");

Coordinate Systems

Refer to the MATLAB Documentation page called "Coordinate Systems in Optical Design" to learn about the coordinate system conventions used to construct optical systems.

Field Point Angle Convention

When creating a field point with fieldPoint(Angles=[Hy Hx]):

  • Hy — vertical field angle (degrees)

  • Hx — horizontal field angle (degrees)

Example — a field point at 10 degrees vertical:

fp = fieldPoint(Angles=[10 0]);

A field point at 10 degrees horizontal:

fp = fieldPoint(Angles=[0 10]);
TiltAngles Convention

TiltAngles=[Rx Ry Rz] specifies rotations in degrees about each axis:

  • Rx (first element) — rotation about the X-axis

  • Ry (second element) — rotation about the Y-axis

  • Rz (third element) — rotation about the Z-axis

Example — a mirror tilted 45 degrees about the X-axis:

addMirror(opsys, TiltAngles=[45 0 0]);

Common Interaction Patterns

Pattern: Build → Visualize → Analyze

Many user requests follow this sequence:

  1. Build or import an optical system

  2. Define field points and wavelengths

  3. Run an analysis function

  4. Inspect returned values

  5. Visualize results

%% 1. Build
opsys = opticalSystem(Wavelengths=587.562);
addRefractiveSurface(opsys, Radius=50, Material=pickGlass("N-BK7"), SemiDiameter=10, DistanceToNext=5);
addRefractiveSurface(opsys, Radius=-50, SemiDiameter=10, DistanceToNext=20);
addImagePlane(opsys, SemiDiameter=10);
opsys.FieldPoints = fieldPoint(Angles=[0 0; 10 0]);

%% 2. Visualize
h2 = view2d(opsys);

%% 3. Analyze
tra = rayAberration(opsys);
hra = show(tra);
Pattern: Compute → Show

Many analyses follow a compute first, visualize second pattern.

spotResult = spot(opsys);
spotDiagram(spotResult);
ldResult = lensDistortion(opsys);
show(ldResult);

Use this pattern when the user wants both a numeric result and a plot.

Pattern: Fresh Copy of Optical System

Explicitly create a fresh copy of the original system if you want to use it as a starting point for multiple different changes. This is particularly useful for tolerancing and sensitivity analysis, where parameters of the original system are mutated repeatedly.

newSys = copy(opsys);

This avoids accumulating perturbations across trials unless accumulation is explicitly intended.

Task: Construct Optical System from Prescription Table

Sequential optical systems are often specified as prescription tables (common in patent documents, textbooks, and optical design references).

Each row represents a surface or optical element, with columns such as:

  • Radius of curvature

  • Thickness to next surface

  • Material (name or [nd, vd])

  • Surface type (implicit or explicit, e.g., stop or image plane)

Users may provide this data as a screenshot, an Excel sheet, or a manually entered table.

Example Prescription Table (Explicit Stop Surface)
SurfaceRadiusThicknessMaterialType
1505N-BK7Refractive
2-505AirRefractive
3—5—Stop
4405N-BK7Refractive
5-4020AirRefractive
6Inf0ImageImagePlane
Pattern: Table → Optical System
  1. Create opticalSystem

  2. Iterate over rows

  3. For each row:

    • Refractive → addRefractiveSurface

    • Stop → addDiaphragm

    • ImagePlane → addImagePlane

  4. Use thickness as DistanceToNext for preceding element

Example Code
opsys = opticalSystem(Wavelengths=587.562);

% Surface 1
addRefractiveSurface(opsys, Radius=50, Material=pickGlass("N-BK7"), DistanceToNext=5);
% Surface 2
addRefractiveSurface(opsys, Radius=-50, DistanceToNext=5);
% Stop (explicit element)
addDiaphragm(opsys, DistanceToNext=5);
% Surface 4
addRefractiveSurface(opsys, Radius=40, Material=pickGlass("N-BK7"), DistanceToNext=5);
% Surface 5
addRefractiveSurface(opsys, Radius=-40,DistanceToNext=20);
% Image plane
addImagePlane(opsys);

h2initial = view2d(opsys, Parent=figure);
Update Semi Diameters of Surfaces

The semi-diameters of all the surfaces is set to the default value because the table does not provide this value. Instead, system descriptions usually provide a field of view (FOV).

Pattern: Set Semi-Diameters from Field of View

After building the optical system:

  1. Use the field of view to define the target field angle

  2. Identify the aperture constraint from the system description. See help updateSemiDiameters for valid constraint options.

  3. Call updateSemiDiameters to compute semi-diameters for all surfaces

FOV = 20;   % degrees
targetFieldAngle = FOV / 2;
updateSemiDiameters(opsys, "EntryPupilRadius", 5, TargetFieldAngle=targetFieldAngle);
h2Final = view2d(opsys, Parent=figure);

Task: Create systems using components

Users often build optical systems by combining off-the-shelf components (e.g., vendor-provided designs such as singlets, doublets, or lens groups).

This workflow involves:

  • importing existing designs

  • modifying system structure

  • explicitly managing gaps between components

Pattern: Extend System with Component
  1. Load the components or systems that will be used to construct the base system

  2. Remove terminal components if needed (e.g., image plane)

  3. Explicitly update gaps as removing components does not update the gap

  4. Create the base system opticalSystem

  5. Add loaded components one by one to the base system and set the gap between components suitably

Example Code
% Load existing system
opsysCooke = zmximport("CookeTriplet.zmx");
% Step 1: Remove image plane (if present)
remove(opsysCooke);
% Step 2: Removing a component does NOT remove the gap. Zero out the trailing gap
changeGap(opsysCooke, numel(opsysCooke.Components), 0);

% Step 3: Import singlet component
opsysSinglet = zmximport("singlet.zmx");

% Step 4: Create a new optical System with these two
opsys = opticalSystem(Name="Combined System");
add(opsys, opsysCooke);
changeGap(opsys, numel(opsys.Components), 3, GapLocation="after");

% Step 4: Append singlet to system
add(opsys, opsysSinglet);

h2 = view2d(opsys);

Task: Add Mirrors or Folded Geometry

Use addMirror when the user wants to model reflective systems.

Example: Periscope system with mirrors at 45 degrees

This periscope folds the beam in the Y-Z plane using X-axis rotations:

opsys = opticalSystem();
addMirror(opsys, Radius=0, SemiDiameter=10, TiltAngles=[45 0 0]);
addGap(opsys, 50);
addMirror(opsys, Radius=0, SemiDiameter=10, TiltAngles=[-45 0 0]);
addGap(opsys, 20);
addImagePlane(opsys, SemiDiameter=10);

h = view2d(opsys);
addRays(h);

To fold in the X-Z plane instead, use Y-axis rotations: TiltAngles=[0 45 0].

Task: Use Ray Data

Use this when the analysis user is looking for is not available out of the box and the user has to derive it themselves using the RayData that is available as part of the RayBundle.

Pattern — plot incident angles on a specific surface using pupil coordinates:

% Import a Cooke triplet
opsys = zmximport("CookeTriplet.zmx");

% Trace from 10-degree field point with incident angle data
fp = fieldPoint(Angles=[10 0]);
sg = samplingGrid("Hexapolar", 8);
rb = traceRays(opsys, FieldPoints=fp, Wavelengths=587.562, SamplingGrid=sg, RayProperties="IncidentAngle");
rd = rb(1).RayData;

% OrientedGrid gives normalized pupil XY for each ray
xy = rd.OrientedGrid;
% Incident angles on surface 4
angles = rd.IncidentAngle(:, 4);

% Scatter plot: position from pupil grid, size and color from angle
figure;
scatter(xy(:,1), xy(:,2), abs(angles)*5, angles, 'filled');
colorbar;
xlabel("Pupil X"); ylabel("Pupil Y");
title("Incident Angle on Surface 4 — Field Angle 10°");
axis equal;

Task: Optimize a Design

Use design optimization when the user wants to improve performance starting from an initial optical system. See references/optical-system-design.md for detailed patterns, code templates, and optimizer selection guidance.

General workflow:

  1. Define an initial optical system

  2. Pack design variables (radii, thicknesses, materials, gaps) into a numeric vector

  3. Create a helper function (x2opsys) to convert the vector back to an opticalSystem

  4. Define a merit function using weighted performance metrics (focal length, spot RMS, track length)

  5. Run a bounded optimizer (lsqnonlin for multi-objective, fmincon for scalar)

  6. Reconstruct the optimized system and verify with paraxialInfo, spot, and view2d

Always call updateSemiDiameters inside the parameter-to-system conversion to maintain the aperture constraint after every parameter change.

Task: Optical Coating Design

Use this when the user wants to design, analyze, or optimize thin-film optical coatings (AR coatings, bandpass filters, longpass/shortpass filters, notch filters). See references/optical-coating-design.md for detailed patterns and optimization templates.

General workflow:

  1. Define coating materials using pickCoatingMaterial

  2. Specify layer structure via LayerMaterialIndex (alternating high/low index)

  3. Create the coating with opticalCoating and layer thicknesses

  4. Query spectral response with fresnelCoefficients

  5. For optimization: pack thicknesses into a vector, define spectral band goals, run a bounded optimizer

Key functions:

  • pickCoatingMaterial("SiO2") — load a coating material

  • opticalCoating(...) — create multi-layer coating

  • fresnelCoefficients(oc, Wavelengths=..., IncidentAngles=...) — compute transmittance/reflectance

  • Access fq.Ta (total transmittance), fq.Ra (total reflectance), or polarization-resolved properties

Task: Optical Coating Tolerancing

Use this when the user wants to evaluate manufacturing sensitivity or yield of a coating design. See references/optical-coating-tolerance.md for detailed patterns and Monte Carlo templates.

General workflow:

  1. Define the nominal coating design

  2. Specify manufacturing tolerances (thickness sigma per material, refractive index sigma)

  3. Choose analysis type:

    • Sensitivity: perturb each layer individually, measure impact on performance

    • Monte Carlo yield: run N randomized trials with Gaussian perturbations, compute pass rate

  4. Evaluate each sample against a pass/fail spec using fresnelCoefficients

  5. Compute yield percentage and visualize tolerance envelope

Key considerations:

  • Use parfor for Monte Carlo trials (each trial is independent)

  • Model thickness and refractive index variations as independent Gaussian perturbations

  • Material-specific sigma values (high-index materials typically have larger variability)

  • 400+ trials for reliable yield estimates; 1000+ for final qualification

Additional Notes

  • imref2d can be useful when converting physical locations on a 2D plane into pixel locations.

  • For dynamic optical systems in Simulink, see references/dynamic-optical-systems-simulink.md

Embedding view3d / view2d in UI Apps

When placing view3d or view2d inside a uifigure layout, use a uigridlayout (not a uipanel) as the parent so the viewer chart fills the available space:

gl = uigridlayout(parentContainer, [1 1], Padding=[0 0 0 0]);
osv3d = view3d(opsys, Parent=gl);

Chart objects auto-stretch to fill grid layout cells but do not auto-resize inside plain uipanel containers.


Copyright 2026 The MathWorks, Inc.


Files

references/optical-system-design.md

Optical System Design Optimization

Use this reference when the user wants to optimize an optical system's performance by varying design parameters. The reference teaches how to decompose any optimization request into a standard problem structure.

Problem Structure

Every optical design optimization maps to this structure:

User Request → Design Variables + Ranges + Goal → x2opsys + Merit Function → Optimizer

Your job is to identify each piece from the user's request and assemble them.

Step 1: Identify Design Variables

From the user's request, determine what can change. Pack these into a flat numeric vector x.

Examples of how user language maps to variables:

User says...Design variables
"optimize the lens shape"Radii of curvature
"find the best thickness"Lens center thicknesses
"adjust spacing between elements"Air gaps
"find the best glass"Refractive index (Nd), Abbe number (Vd)
"optimize the whole system"All of the above

These are common cases — the user's request may suggest other variables not listed here.

% Pack into a vector
x = [radii, thicknesses, gaps, materials];

Record how to unpack x back into named parameters (indices into the vector).

Step 2: Define Ranges

Every design variable needs physical bounds. These prevent the optimizer from exploring unphysical or unfabricable designs.

Suggested starting ranges (adjust based on system scale and user context):

ParameterTypical RangeRationale
Radius of curvature±5 mm to ±500 mmNear-zero = infinite power (singularity)
Lens thickness1 mm to 15 mmMust be positive and fabricable
Air gap0.5 mm to 30 mmMust be positive
Refractive index (Nd)1.45 to 1.85Range of common optical glasses
Abbe number (Vd)20 to 80Low = flint, high = crown
lb = [...];  % Lower bounds for each element of x
ub = [...];  % Upper bounds for each element of x

Step 3: Define the Goal

The goal is the central organizing concept. It bundles together:

  • Metrics — what to measure (focal length, spot RMS, distortion, track length, MTF, etc.)

  • Field points — where to evaluate those metrics (on-axis, intermediate, full-field edge)

  • Targets — what values the metrics should achieve

  • Weights — relative importance of each metric

Extract these from the user's request. Examples:

User says...MetricsField points
"sharper image across the field"Spot RMSOn-axis + intermediate + edge
"wider field of view"Spot RMS, distortionMultiple angles up to new FOV
"match this focal length at f/4"Focal length, F-numberOn-axis
"minimize chromatic aberration"Spot RMS at multiple wavelengthsOn-axis + edge
"compact design"Track length + spot RMSOn-axis + edge

The user's request may involve metrics or field point strategies not shown above — use domain knowledge to identify the right combination.

goal.Metrics = {...};           % What to measure
goal.FieldPoints = fieldPoint(...);  % Where to evaluate
goal.Targets = [...];           % What values to achieve
goal.Weights = [...];           % Relative importance

Weight guidelines:

  • Hard constraints (must be met exactly): high weight (5–10)

  • Primary performance (the user's main ask): medium-high weight (1–3)

  • Soft constraints (nice to have): low weight (0.1–0.5)

Step 4: Write the Conversion Function (x2opsys)

This function maps the numeric vector x back into a fully constructed opticalSystem. It is called at every optimizer iteration.

function opsys = x2opsys(x, design, goal)
    % Unpack x into named parameters
    radii       = x(1:design.NumRadius);
    thicknesses = x(...);
    gaps        = x(...);

    % Build system
    opsys = opticalSystem(Wavelengths=design.Wavelengths);

    % Add surfaces using unpacked parameters
    for i = 1:design.NumLenses
        addRefractiveSurface(opsys, Radius=radii(2*i-1), ...
            Material=..., DistanceToNext=thicknesses(i));
        addRefractiveSurface(opsys, Radius=radii(2*i), ...
            DistanceToNext=gaps(i));
    end

    addImagePlane(opsys);

    % Apply any system-level constraints from the goal
    % (e.g., updateSemiDiameters if aperture is fixed, set field points, etc.)
end

The conversion function must produce a valid, analyzable system for any x within bounds.

Step 5: Write the Merit Function

The merit function evaluates the system against the goal. It returns:

  • A vector of weighted residuals (for lsqnonlin) — one residual per metric per field point

  • Or a scalar (for fmincon) — single combined error

function F = meritFunction(opsys, goal)
    F = [];

    % For each metric in the goal, evaluate at the goal's field points
    % Compare to targets, weight, and append to residual vector

    % Example: focal length error
    pInfo = paraxialInfo(opsys);
    focalErr = goal.Weights.Focal * (pInfo.FocalLength - goal.Targets.FocalLength) / goal.Targets.FocalLength;
    F = [F, focalErr];

    % Example: spot RMS at each field point
    spotResults = spot(opsys, FieldPoint=goal.FieldPoints);
    spotErr = goal.Weights.Spot .* ([spotResults.RMS] - goal.Targets.SpotRMS) / goal.Targets.SpotRMS;
    F = [F, spotErr];
end

The merit function is where the goal struct drives the evaluation — metrics, field points, targets, and weights all come from it.

Step 6: Choose and Run the Optimizer

ScenarioOptimizerWhy
Multiple metrics (focal + spot + distortion)lsqnonlinHandles vector residuals natively
Single scalar objectivefminconGeneral constrained minimization
Many local minima (glass search, many elements)ga or surrogateoptGlobal search
Interactive explorationOptimization Explorer appVisual, supports multiple solvers
x0 = (lb + ub) / 2;  % or extract from the starting system

meritFcn = @(x) meritFunction(x2opsys(x, design, goal), goal);

options = optimoptions('lsqnonlin', Display='iter', MaxFunctionEvaluations=5000);
[xOpt, resnorm] = lsqnonlin(meritFcn, x0, lb, ub, options);

% Reconstruct optimized system
opsysOpt = x2opsys(xOpt, design, goal);

Verifying Results

After optimization, verify against the goal:

pInfo = paraxialInfo(opsysOpt);
spotResult = spot(opsysOpt, FieldPoint=goal.FieldPoints);
spotDiagram(spotResult);
view2d(opsysOpt);

Mapping User Requests — Examples

User requestVariablesGoal metricsGoal field points
"Optimize Cooke triplet for wider FOV"Radii, gapsSpot RMS, focal lengthOn-axis + new edge angle
"Find best glass for a doublet at f/5"Nd, VdChromatic spot RMSOn-axis + 10°
"Minimize total track length"Thicknesses, gapsTrack length, spot RMSOn-axis + edge
"Sharpen the edges without hurting center"Radii, gapsSpot RMSEdge-heavy weights
"Design a 50mm f/1.8 with <20µm spot"AllFocal length, F-number, spot RMSMultiple field angles

Reference Example

See the MATLAB example "Optimize Monochromatic Camera Lens System for Type 2/3 Sensor" for a complete end-to-end workflow.


Copyright 2026 The MathWorks, Inc.


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/image-processing-and-computer-vision/matlab-model-optics · 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 or MathWorks.

Download ZIP

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