matlab-upgrade-mex-ic
This skill converts MATLAB MEX source files from the older Separate Complex API to the Interleaved Complex API, modernizing legacy C, C++, and Fortran code to eliminate performance overhead on complex arrays. Use it when upgrading pre-R2018a MEX files, building with mex -R2018a, or improving performance for MEX functions that handle large complex data, following MathWorks upgrade workflow with verification steps.
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-upgrade-mex-ic && cp -r /tmp/matlab-upgrade-mex-ic/skills-catalog/matlab-external-language-interfaces/matlab-upgrade-mex-ic ~/.claude/skills/matlab-upgrade-mex-icSKILL.md
# Upgrade MEX Files to Interleaved Complex API
Convert C, C++, and Fortran MEX source files from the Separate Complex (SC) API to the Interleaved Complex (IC) API, following the MathWorks upgrade workflow with guardrails for SC/IC guarded builds using `MX_HAS_INTERLEAVED_COMPLEX`, required vs recommended changes, and verification.
## When to Use
- User has a C, C++, or Fortran MEX file using `mxGetPr`/`mxGetPi`, `mxGetData`/`mxGetImagData`, or `mxSetPr`/`mxSetPi`
- User wants to build with `mex -R2018a`
- User asks about interleaved complex, IC MEX, or modernizing MEX code
- User has legacy MEX code from File Exchange, GitHub, or pre-R2018a era
- User has a C++ MEX file (`.cpp`, `.cxx`) using the C Matrix API (`mxGetPr`/`mxGetPi`, etc.)
- User has a Fortran MEX file (`.F`, `.f90`) using `mxGetPr`/`mxGetPi` via `%val()` pointers
- User reports a MEX function is slow on large complex arrays (call overhead, not loop)
- User asks how to improve MEX performance for complex data
## When NOT to Use
- Writing a new MEX function from scratch — no conversion needed, but advise the user to use IC APIs (`mxGetDoubles`, `mxGetComplexDoubles`, etc.) from the start for better performance on complex data and modern, type-safe data access instead of legacy `mxGetPr`/`mxGetPi`
- C++ MEX API (`matlab::mex::Function`) — different API entirely; this skill covers C++ files that use the C Matrix API (`mex.h`), not the MATLAB Data API for C++ and C++ Engine
- MEX file already uses typed accessors (`mxGetDoubles`, `mxGetComplexDoubles`, etc.) — already IC-compatible, no conversion needed
## Workflow
Follow these 7 steps in order. Do NOT skip steps.
### Step 1: Pre-Upgrade Verification
Before changing anything, understand the current state:
1. Read the source file completely
2. Identify all SC API calls (see [Key API Mappings](#key-api-mappings))
3. Note which data types the MEX handles (double, single, int32, etc.)
4. Note whether it handles complex data (`mxGetPi`, `mxIsComplex`, `mxCOMPLEX`)
Report to the user:
- Number of SC API calls found
- Whether file processes complex numbers (complex arrays in SC mode incur deinterleave/re-interleave overhead)
- **Performance impact:** If the file handles complex data, note that SC MEX calls incur O(n) deinterleave/re-interleave copies at the MATLAB boundary. For large arrays, IC conversion eliminates this overhead entirely (see [Performance Benefits](#performance-benefits-of-ic-conversion)).
- Any other issues noticed (missing error checking, etc.)
### Step 2: Output File Decision
**ASK the user before proceeding:**
> "Where should I write the converted code?
> - **New file** — creates a separate file (e.g., `<name>_ic.c` or `<name>_dual.c`), preserving the original untouched
> - **Modify in place** — edits the original file directly. Choose this if the file is under version control and you can revert if needed."
If user chooses **new file**, use these naming defaults (or a user-specified name):
- IC-only: `<name>_ic.c` / `<name>_ic.F`
- SC/IC guarded: `<name>_dual.c` / `<name>_dual.F`
If user chooses **modify in place**, confirm the file is recoverable (e.g., "This file is tracked by git — you can revert with `git checkout <file>` if needed."). Then edit the original directly.
Tell the user which file you're writing to and why.
### Step 3: Decision Point — IC-Only or SC/IC Guarded?
> **What is "SC/IC guarded"?** A single source file that uses `#if MX_HAS_INTERLEAVED_COMPLEX` preprocessor guards to compile under both the Separate Complex API (`mex -R2017b`) and the Interleaved Complex API (`mex -R2018a`). The compiler defines `MX_HAS_INTERLEAVED_COMPLEX=1` in IC mode and `0` in SC mode, so the guards select the correct code path at build time.
**ASK the user before proceeding:**
> "Do you need this MEX file to compile under both the old SC API and the new IC API?
> - **SC/IC guarded** — wraps code in `#if MX_HAS_INTERLEAVED_COMPLEX` / `#else` guards so the same source builds with both `mex -R2017b file.c` (SC mode) and `mex -R2018a file.c` (IC mode). Choose this if you support multiple MATLAB versions.
> - **IC-only** — converts fully to IC API. Requires `mex -R2018a` to build. Simpler code but only works on R2018a+."
If user chooses **SC/IC guarded**, use the `#if MX_HAS_INTERLEAVED_COMPLEX` preprocessor pattern:
**C/C++ files:**
```c
#if MX_HAS_INTERLEAVED_COMPLEX
/* IC code path */
mxComplexDouble *pc = mxGetComplexDoubles(prhs[0]);
#else
/* SC code path */
double *pr = mxGetPr(prhs[0]);
double *pi = mxGetPi(prhs[0]);
#endif
```
**Fortran files** (`.F` preprocessed source):
```fortran
#if MX_HAS_INTERLEAVED_COMPLEX
mwPointer mxGetComplexDoubles
complex*16, pointer :: pc(:)
call mxGetComplexDoubles(prhs(1), pc)
#else
mwPointer mxGetPr, mxGetPi
mwPointer pr, pi
pr = mxGetPr(prhs(1))
pi = mxGetPi(prhs(1))
#endif
```
> **Fortran note:** SC/IC guarded Fortran files MUST use `.F` extension (uppercase) so the MEX compiler invokes the C preprocessor. The `.f` or `.f90` extension skips preprocessing and `#if` guards will not work. For `.f90` files that cannot use preprocessor guards, use IC-only conversion.
If user chooses **IC-only**, convert directly without guards.
### Step 4: Iterative Refactoring
All legacy data-access APIs are **REQUIRED** to be converted for a complete IC upgrade. Convert every pattern in this table:
| Legacy Pattern | Replacement | Reason |
|----------------|-------------|--------|
| `mxGetPi(arr)` for data access | `mxGetComplexDoubles(arr)` + `.imag` | Does not exist in IC |
| `mxSetPi(arr, ptr)` | `mxSetComplexDoubles(arr, ptr)` | Does not exist in IC |
| `mxGetImagData(arr)` | Type-specific complex accessor | Does not exist in IC |
| `mxSetImagData(arr, ptr)` | Type-specific complex setter | Does not exist in IC |
| `mxGetPi(arr) != NULL` for complexity check | `mxIsComplex(arr)` — works in both SC and IC | Does not exist in IC |
| `mxGetPr(arr)` | `mxGet>
Analyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.
Analyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.
Analyze the effective toolbox file set to produce a Dependency Manifest — classify all transitive dependencies as included, product, add-on, or external-unresolved, then present resolution options with tradeoffs. Use after matlab-define-toolbox-api when the spec is approved.
S-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).
Analyze antennas installed on electrically large conducting platforms using MATLAB Antenna Toolbox. Loads platform geometry from STL/STEP/IGES, installs antenna elements, selects electromagnetic solvers (MoM-PO, FMM, MoM), and computes patterns, impedance, coupling, and efficiency. Use when the user wants to model an antenna on a vehicle, aircraft, ship, satellite, or other large structure.
PDN DC voltage/current analysis, IR drop, design rule checking, and multi-net batch analysis on imported PCB layouts. TRIGGER: user asks about power integrity, PDN analysis, IR drop, voltage distribution, current density, power nets, or design rule checking on a PCB. Invoke BEFORE writing code — the PDN API chain is specialized and non-obvious. SKIP: importing a PCB file (use matlab-read-pcb-layout), EM field/S-parameter extraction (use matlab-analyze-em), material/stackup setup only (use matlab-manage-pcb-material), transmission line design (use matlab-design-pcb-txline).
Calculate and visualize monostatic and bistatic radar cross section (RCS) using MATLAB Antenna Toolbox. Computes RCS of platforms, antennas, and arrays with PO, MoM, and FMM solvers, supporting HH/VV/HV/VH polarization, GPU acceleration, and near-field observation. Use when the user wants to compute, plot, or analyze radar cross section.