Skip to main content
ClaudeWave
ES, Spanish
Skill1.2k estrellas del repoactualizado 6d ago

matlab-diagnose-parfor

# matlab-diagnose-parfor This Claude Code skill diagnoses and fixes MATLAB `parfor` loop variable classification errors by running the code analyzer and applying targeted fixes. Use it when users encounter parfor runtime errors, classification failures, performance issues tied to variable scope problems, or need help converting standard `for` loops to parallel `parfor` loops. Never attempt to resolve parfor classification issues from memory alone.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-diagnose-parfor && cp -r /tmp/matlab-diagnose-parfor/skills-catalog/parallel-computing/matlab-diagnose-parfor ~/.claude/skills/matlab-diagnose-parfor
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Diagnose and Fix parfor Variable Classification

**Do NOT reason about parfor classification rules from memory.** LLM training
data contains incomplete and often incorrect explanations of these rules.
MATLAB's code analyser (`checkcode` / `codeIssues` / `mcp__matlab__check_matlab_code`)
is the only reliable authority — it implements the exact same classifier that
the runtime uses. Always run it first; never guess.

## When to Use

- ANY code involving `parfor` where the user reports a problem or asks for help
- User gets a parfor classification error (runtime or in editor)
- User wants to convert a `for` loop to `parfor`
- User asks why parfor complains, won't run, or is slow due to classification
- You are about to suggest changes to parfor code — run the analyser first

## When NOT to Use

- parfor runs but is **slow** — performance/pool-choice question, not a classification error
- Worker needs setup/state (paths, environment, toolboxes) — not a parfor variable problem
- Code simply mentions `parfor` but the user does not mention any problems with it

## Workflow

**Always follow this order. Never guess at classification rules.**

1. **Run the code analyser** on the file containing the parfor loop using
   the `mcp__matlab__check_matlab_code` MCP tool. Do NOT shell out to MATLAB
   via Bash — always use the MCP tool. Read the exact error message.

2. **Identify the error type** from the message (see table below).

3. **Apply the matching fix pattern** (see Patterns section).

4. **Verify** by re-running `mcp__matlab__check_matlab_code` on the fixed
   code — confirm zero parfor classification errors.

## Error Messages and Root Causes

For the full catalog of all 48 parfor analyser messages (with IDs), see
`references/parfor-analyser-messages.md`. The table below covers the most
common classification errors.

| checkcode message | Root cause | Fix pattern |
|-------------------|-----------|-------------|
| "Unable to classify variable 'X'" | Catch-all: many causes. Often invalid slicing (inconsistent subscripts, indexing not involving the loop variable) or invalid combinations of accesses (e.g. indexed reduction). Struct-field accesses are one specific way to trigger this. | Identify the specific access pattern, then restructure to fit one category or split conflicting roles |
| "multiple sliced accesses...do not all have the same list of subscripts" | Same variable sliced with different subscript patterns (e.g. `A{i,1}`, `A{i,2}`) | Use single assignment: `A(i,:) = {...}` |
| "Variable 'X' is indexed...but it is not a valid sliced output variable" | One subscript is non-deterministic (random, function call), or loop variable appears in multiple dimensions, or subscript pattern otherwise violates slicing rules | Pre-compute problematic subscripts, restructure to use loop variable in exactly one dimension with fixed remaining subscripts |
| "accessed with an invalid combination of sliced indexing expressions and non-indexed reads" | Variable is written with sliced indexing AND read whole in the same iteration — conflicting roles | Separate into two variables: one for sliced writes, a snapshot or broadcast copy for whole reads |
| "The temporary variable 'X' might be used after the PARFOR loop" / "Temporary variable 'X' must be set inside the parfor loop before it is used" | Variable is conditionally assigned (only in an if-branch), so MATLAB treats it as temporary — but it's used after the loop or read before being set on some paths | Restructure as sliced output (store per-iteration values) + post-loop reduction |
| "When indexing a sliced variable with a nested for loop variable, the range...must be a row vector of positive constant numbers or variables" | Inner `for j = 1:(expr)` where `expr` is not a literal constant or a broadcast variable | Make the inner loop range a constant or broadcast variable, or accumulate into a local temporary and assign the sliced variable once per outer iteration |
| "The entire array or structure 'X' is a broadcast variable" | Variable used whole (not indexed by loop variable); read-only | Not an error — performance warning. Use `parallel.pool.Constant(X)` if large |

## Variable Classification Rules (Reference)

parfor classifies each variable into exactly one category:

| Category | Rule | Example |
|----------|------|---------|
| **Loop** | The loop index variable | `parfor i = 1:N` |
| **Sliced** | Indexed by the loop variable in any one dimension (not just the first); the same subscript pattern is used in every access. The loop variable may be offset by a literal constant or a broadcast variable (e.g. `A(i+1,:)`, `A(:,i-k)` where `k` is broadcast). | `A(i,:) = ...`, `A(:,i) = ...`, `A(i+1) = ...` |
| **Broadcast** | Used whole (not indexed by loop variable); read-only | `total = sum(bigArray)` |
| **Reduction** | Form `X = X op expr` or `X = expr op X` where X is the entire variable, `op` is associative operator `+`, `.*`, `&`, `\|` etc. | `total = total + val` |
| **Temporary** | First use in iteration is an assignment; not used after loop | `temp = rand(10)` |

**Critical constraint:** A variable must fit exactly ONE category. Mixed usage
(e.g. struct fields used as reductions, or same variable sliced with different
subscripts) causes classification failure.

## Patterns

### Fix 1: Struct field as sliced output → plain array

**Error:** "Unable to classify variable 'out'"

The most common cause of "Unable to classify" with structs. Users write
`out.field(i) = someFcn()` expecting to slice into a struct field, but
first-level indexing on `out` is dot (`.field`), not parentheses. Sliced
variables require first-level `()` or `{}` indexing with the loop variable —
dot-indexing is never valid for slicing.

```matlab
% BROKEN: first-level subscript on out is dot, not paren
parfor i = 1:N
    out.x(i) = computeX(i);
    out.y(i) = computeY(i);
end
```

**Fix:** Use separate arrays for sliced output, pack into struct after the loop:

```matlab
xVal
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.