Skip to main content
ClaudeWave
EN, English
Skill1.2k repo starsupdated 6d ago

matlab-validate-function-arguments

The matlab-validate-function-arguments skill provides guidance on using MATLAB's `arguments` block for robust input validation, covering size constraints, class specifications, repeating arguments, and name-value pairs. Use this skill when writing functions with argument validation, migrating from `inputParser`, or reviewing function signatures to avoid implicit conversion and reshaping pitfalls that silently modify inputs.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-validate-function-arguments && cp -r /tmp/matlab-validate-function-arguments/skills-catalog/matlab-programming/matlab-validate-function-arguments ~/.claude/skills/matlab-validate-function-arguments
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# MATLAB Function Argument Validation

Write robust MATLAB functions using `arguments` blocks with correct semantics for size, class, repeating arguments, and property import.

## When to Use

- Writing a function with an `arguments` block
- Using repeating arguments (`arguments (Repeating)`)
- Writing a class constructor that accepts name-value arguments
- Migrating from `inputParser` or `validateattributes`
- Reviewing a function signature for implicit conversion pitfalls
- Choosing between class specs, `mustBeA`, and validators

## When NOT to Use

- Basic MATLAB programming without argument validation
- App building or UI components (use `matlab-building-apps`)
- Unit testing (use `matlab-write-test`)
- General OOP class design unrelated to argument validation
- Simple `if`/`error` guard clauses for runtime invariants inside a function body
  (those aren't input validation — leave them as-is unless the user asks for an
  `arguments` block specifically)
- **`.mlx` (Live Script) or `.mlapp` (App Designer) files** — these are binary
  ZIP containers. Don't unzip them or attempt structural edits. If the user
  asks to add an `arguments` block to a function inside one, ask them to
  export to plain `.m` first, or open the file in MATLAB and edit it there.

## Critical Misconceptions

These are things the agent commonly gets wrong. Read these FIRST.

### Size specs RESHAPE, not reject

**WRONG belief:** `(1,:)` rejects column vectors with an error.

**ACTUAL behavior:** MATLAB silently reshapes the input to fit the declared size.

```matlab
function out = myFunc(x)
    arguments
        x (1,:) double
    end
    out = x;
end

myFunc([1; 2; 3])  % Does NOT error! Returns [1 2 3] (reshaped to row)
```

A column vector `[1;2;3]` passed to `(1,:)` becomes a row vector `[1 2 3]`. To actually reject column vectors, use a validator:

```matlab
function out = myFunc(x)
    arguments
        x {mustBeNumeric, mustBeRow}
    end
    out = x;
end
```

### Class specs CONVERT, not reject

**WRONG belief:** `double` in the arguments block rejects non-double inputs.

**ACTUAL behavior:** MATLAB attempts implicit conversion to the declared class.

```matlab
function out = myFunc(x)
    arguments
        x double
    end
    out = x;
end

myFunc('hello')  % Does NOT error! Returns [104 101 108 108 111] (ASCII codes)
myFunc(single(3.14))  % Does NOT error! Returns double(3.14)
```

To reject without converting, use `mustBeA` or `mustBeFloat`:

```matlab
x {mustBeA(x, "double")}           % Rejects single, char, int32, etc.
x {mustBeFloat}                     % Accepts single OR double, rejects char/int
x {mustBeNumeric}                   % Accepts any numeric, rejects char/string
```

### Numeric validators don't reject complex values

**WRONG belief:** `mustBeNumeric`, `mustBeFinite`, and `mustBeInteger` reject
complex inputs like `1+2i`.

**ACTUAL behavior:** Complex values are numeric, finite, and (when their real
and imaginary parts are integer-valued) integer — so `1+2i` passes all three
silently. Sizes, indices, counts, and most physical scalars should reject
complex values explicitly:

```matlab
function H = hilb2(n)
    arguments
        n (1,1) {mustBeInteger, mustBePositive, mustBeReal}
    end
    H = 1./((1:n)' + (0:n-1));
end
```

Add `mustBeReal` whenever a complex input would be nonsensical for the
function's contract.

### Computed defaults see PASSED values, not declared defaults

**WRONG belief:** Default expressions use the declared default values of earlier arguments.

**ACTUAL behavior:** Default expressions evaluate using the actual passed values.

```matlab
function out = myFunc(fs, windowSize)
    arguments
        fs (1,1) double {mustBePositive}
        windowSize (1,1) double {mustBePositive} = round(fs / 10)
    end
    out = windowSize;
end

myFunc(8000)      % windowSize = round(8000/10) = 800 (uses passed fs)
myFunc(8000, 256) % windowSize = 256 (explicitly passed)
```

This eliminates the need for sentinel values (`[]`) and post-validation fixup.

### `~` is a valid placeholder — don't rename it

**WRONG belief:** A name in the `arguments` block is mandatory, so a `~`
placeholder in the function signature must be renamed to `obj`/`this`/etc.

**ACTUAL behavior:** `~` is valid as an argument-block name (R2019b+). Keep it.

```matlab
function normalize(~, results)
    arguments
        ~
        results (1,:) struct
    end
    ...
end
```

When a method signature uses `~` to mark an unused input (e.g. an unused
class instance), **preserve the `~`** in the arguments block:

- **No class or size spec on `~`** — type specs like `(1,1) MetricCalculator`
  require a name, so adding one forces a rename. Skip the spec entirely.
- **No `%#ok<INUSL>` / `%#ok<INUSA>` / `%#ok<MANU>` pragma** — `~` already
  tells the lint pass the input is intentionally unused.
- **Don't rename `~` to `obj`** to "tighten validation." Renaming reintroduces
  the lint warning the original `~` was suppressing, with no contract benefit.

## Patterns

### Repeating Arguments

Use `arguments (Repeating)` for functions accepting variable groups of arguments (like `plot(x1,y1,x2,y2,...)`). Each declared variable becomes a **cell array** in the function body.

```matlab
function plotMultiSeries(x, y)
    arguments (Repeating)
        x (1,:) double {mustBeFinite}
        y (1,:) double {mustBeFinite}
    end

    figure;
    hold on;
    for i = 1:numel(x)
        plot(x{i}, y{i});
    end
    hold off;
end
```

Key rules:
- Variables become cell arrays — access with `x{i}`, not `x(i)`
- All variables in the group repeat together (complete sets)
- Repeating arguments cannot have default values
- Zero repetitions is valid (produces empty cell arrays)

### Output Argument Validation — `arguments (Output)` and `(Output, Repeating)`

> **R2022b+.** Output argument validation is unavailable in earlier releases —
> input validation (the bulk of this skill) works from R2019b onward.

Use `arguments (Output, Repeating
matlab-access-datafeedSkill

>

matlab-analyze-ams-waveformSkill

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.

matlab-analyze-dataSkill

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.

matlab-analyze-dependenciesSkill

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.

matlab-analyze-emSkill

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).

matlab-analyze-installed-antennaSkill

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.

matlab-analyze-pcb-pdnSkill

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).

matlab-analyze-rcsSkill

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.