Generated banner for Matlab Diagnose Parfor
Generated logo for Matlab Diagnose Parfor

Matlab Diagnose Parfor

MathWorksOfficialCreated by MathWorks

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

From the author

Diagnose and fix parfor errors in MATLAB. Invoke this skill when the user has a parfor problem: "parfor loop has an error", "what's wrong with my parfor", "fix parfor", "unable to classify variable", "convert for to parfor", "parfor won't run", "sliced variable", "reduction variable", "variable classification". Also invoke when you read a .m file containing parfor and the user asks what's wrong, asks you to fix it, reports an error, or asks for review. Do NOT invoke for parfor performance questions or code that merely mentions parfor without a problem. ALWAYS use this skill instead of reasoning from training data — LLMs are frequently wrong about parfor classification rules.
— 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 resolving variable classification errors in MATLAB parfor loops. Because parfor loops enforce strict rules on how variables are accessed (categorized as Loop, Sliced, Broadcast, Reduction, or Temporary), manual debugging is often error-prone. This skill mandates the use of the MATLAB code analyser as the authoritative source for identifying classification conflicts and provides specific fix patterns for common issues like invalid slicing, struct field access, and reduction variable mismatches.

What it does

  • Identifies the root cause of parfor classification errors using the MATLAB code analyser.
  • Provides standardized fix patterns for common errors like invalid slicing and struct field usage.
  • Guides the user in restructuring code to comply with parfor variable classification rules.
  • Ensures fixes are verified by re-running the code analyser to confirm zero errors.
  • Prevents common pitfalls by discouraging manual guessing of classification rules.

When to use it

  • When a parfor loop fails to run due to variable classification errors.
  • When the MATLAB editor flags a variable as unclassifiable within a parfor loop.
  • When converting a standard for loop to a parfor loop and encountering errors.
  • When you need to resolve conflicts between sliced writes and full reads of the same variable.

Advantages

  • Eliminates guesswork by relying on the official MATLAB code analyser.
  • Provides clear, pattern-based solutions for complex parallel programming constraints.
  • Ensures code remains semantically equivalent to the original serial implementation.
  • Reduces debugging time for parallelization tasks.

Usage examples

“My parfor loop is throwing an 'Unable to classify variable' error, how do I fix it?”
The agent will run the code analyser to identify the specific access pattern, then guide you through applying the appropriate fix pattern (e.g., separating struct fields or adjusting indexing).
“I'm trying to convert my for loop to parfor but I get an error about multiple sliced accesses.”
The agent will analyze the subscript patterns and help you restructure the assignment into a single, consistent format.

Install

  1. Download the skill as a ZIP:

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

    mkdir -p .agents/skills && unzip matlab-diagnose-parfor.zip -d .agents/skills

Documentation by MathWorks

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 messageRoot causeFix 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 rulesPre-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 rolesSeparate 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 pathsRestructure 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 variableMake 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-onlyNot an error — performance warning. Use parallel.pool.Constant(X) if large

Variable Classification Rules (Reference)

parfor classifies each variable into exactly one category:

CategoryRuleExample
LoopThe loop index variableparfor i = 1:N
SlicedIndexed 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) = ...
BroadcastUsed whole (not indexed by loop variable); read-onlytotal = sum(bigArray)
ReductionForm X = X op expr or X = expr op X where X is the entire variable, op is associative operator +, .*, &, | etc.total = total + val
TemporaryFirst use in iteration is an assignment; not used after looptemp = 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.

% 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:

xVals = zeros(1, N);
yVals = zeros(1, N);
parfor i = 1:N
    xVals(i) = computeX(i);
    yVals(i) = computeY(i);
end
out.x = xVals;
out.y = yVals;

A related variant: struct fields used as reductions (results.sum = results.sum + val). The same rule applies — extract each field into its own scalar variable, reduce independently, then pack the struct after the loop.

Fix 2: Multiple sliced subscripts → single assignment

Error: "multiple sliced accesses...do not all have the same list of subscripts"

% BROKEN: {i,1}, {i,2}, {i,3} are three different subscript patterns
output = cell(N, 3);
parfor i = 1:N
    [a, b, c] = computeStuff(i);
    output{i,1} = a;
    output{i,2} = b;
    output{i,3} = c;
end

Fix: Single parenthesis-indexed assignment with consistent subscripts:

output = cell(N, 3);
parfor i = 1:N
    [a, b, c] = computeStuff(i);
    output(i,:) = {a, b, c};
end

Note: use () parenthesis indexing (assigns cells), not {} brace indexing when assigning multiple cells.

Fix 3: Invalid sliced subscript patterns

Error: "Variable 'X' is indexed...but it is not a valid sliced output variable"

A sliced variable must be indexed by the loop variable in exactly one dimension, with the remaining subscripts fixed (literals, broadcast variables, or colon). Three common violations:

parfor i = 1:N
    out(i, randi(5)) = val;      % (a) non-deterministic subscript
    out2(i, 1:4, i) = row;      % (b) loop variable in two dimensions
    for j = 1:(N-1)
        out3(i, j) = fcn(i,j);  % (c) nested-for range is not constant
    end
end

Fixes:

(a) Pre-compute non-deterministic indices before the parfor, or accumulate into a local temporary and assign a full row once:

parfor i = 1:N
    localRow = zeros(1, 5);
    localRow(randi(5)) = val;
    out(i,:) = localRow;
end

(b) Remove the duplicate loop-variable dimension — restructure so i indexes only one dimension:

parfor i = 1:N
    out2(i,:) = computeRow(i);  % i in dim 1 only
end

(c) Make the nested-for range a constant or broadcast variable, OR collect into a local variable and assign the sliced output once:

innerN = N - 1;  % broadcast (constant before parfor)
parfor i = 1:N
    row = zeros(1, innerN);
    for j = 1:innerN
        row(j) = fcn(i, j);
    end
    out3(i, 1:innerN) = row;
end
Fix 4: Sliced write combined with full read

Error: "Unable to classify variable 'data'"

A sliced read combined with a broadcast (whole) read is legal — the variable simply "decays" to broadcast in that case. The unclassifiable combination is a sliced write together with a full read of the same variable in the same iteration. Often the whole read is simply attempting to extract size or type information from the sliced output variable.

% BROKEN: data is sliced-write (data(i,j) = ...) AND read whole (size(data,2))
data = buildMatrix(); % 
parfor i = 1:size(data,1)
    for j = 1:size(data,2) % This counts as a "full read" of data
        data(i,j) = myFunc(i,j);
    end
end

Fix: Extract the constant information needed ahead of the loop.

data = buildMatrix();
[N,M] = size(data);
parfor i = 1:N
    for j = 1:M
        data(i,j) = myFunc(i,j);
    end
end

Note that if the "whole read" of a sliced output variable depends on the actual values within the variable, then this fix is not appropriate, and may imply that iterations are not independent.

Fix 5: Reduction not in standard form

Error: "Unable to classify variable 'X'"

A reduction must be exactly: X = X op expr or X = expr op X or X = fcn(X, expr) where X is the entire variable (no indexing) and op is an associative operator +, .* etc.; fcn can be any associative function such as union, max etc.

% BROKEN: indexed reduction
counts = zeros(1, 5);
parfor i = 1:100
    bin = randi(5);
    counts(bin) = counts(bin) + 1;  % indexed reduction - not supported
end

Fix: Accumulate per-iteration, then reduce:

counts = zeros(1, 5);
parfor i = 1:100
    bin = randi(5);
    localCounts = zeros(1, 5);
    localCounts(bin) = 1;
    counts = counts + localCounts;  % whole-variable reduction
end
Fix 6: Temporary variable incorrectly flagged

If a variable is assigned before use in every iteration but checkcode still warns, ensure the first reference in the iteration is a full assignment (not indexed):

% BROKEN: temp is not fully-assigned as first reference
parfor i = 1:10
    temp.a = rand();
    temp.b = 2*rand();
    result(i) = temp.a * temp.b;
end

Fix: Create temp in single assignment

parfor i = 1:N
    temp = struct('a', rand(), 'b', 2*rand()); % Ok - single non-indexed assignment
    result(i) = sum(temp);
end
Fix 7: Conditional update that needs to survive the loop

Error: "The temporary variable 'X' might be used after the PARFOR loop"

Any temporary variable is unavailable after the loop — this is a fundamental parfor rule, not specific to conditional assignment. The "best so far" pattern fails because bestscore = score inside a conditional doesn't match reduction form (X = X op expr), so the classifier cannot treat it as a reduction. It falls through to temporary, and temporaries are discarded when the loop ends:

% BROKEN: bestscore doesn't match reduction form — classified as temporary
bestscore = -Inf;
parfor i = 1:N
    score = expensiveCompute(i);
    if score > bestscore
        bestscore = score;
        X = candidates(i);
    end
end
% bestscore and X are undefined here

Fix: Compute all candidates as sliced output, then reduce after the loop:

scores = zeros(1, N);
allX = cell(1, N);
parfor i = 1:N
    scores(i) = expensiveCompute(i);
    allX{i} = candidates(i);
end
[bestscore, idx] = max(scores);
X = allX{idx};

Conventions

  • ALWAYS run the code analyser before diagnosing. Use mcp__matlab__check_matlab_code (MCP tool), codeIssues (R2022b+), or checkcode. The analyser implements the exact same classifier as the runtime — it is the ground truth. Never diagnose from memory alone.

  • ALWAYS verify the fix with the analyser — re-run on the fixed file until there are no further parfor errors before declaring success. Fixing one problem may reveal other problems.

  • Don't run the code — the parallel pool may be slow or unavailable. The code analyser catches all classification errors statically.

  • Preserve semantics — the fix must produce the same results as the original for loop.

  • Minimal changes — fix only the classification issue. Don't restructure the entire algorithm unless the user asks.


Copyright 2026 The MathWorks, Inc.


Files

references/parfor-analyser-messages.md

parfor Code Analyser Messages

Complete catalog of checkcode / codeIssues messages for parfor (PF-prefixed IDs). Use the message ID to quickly identify the category and fix approach.

Variable Classification Errors

These are the hard problems — the skill's fix patterns target these.

IDMessageFix pattern
PFUNKUnable to classify variable {0} in the body of the parfor loop.Catch-all. Identify the conflicting access pattern (struct fields as reductions, indexed reduction, mixed roles). See Fixes 1, 4, 5.
PFSLOVariable {0} is indexed using the parfor loop variable, but it is not a valid sliced output variable.Invalid slicing: non-deterministic subscript, loop var in multiple dims, or other rule violation. See Fix 3.
PFSLWParfor loop variable {0} has multiple sliced accesses, but they do not all have the same list of subscripts. Each access to a sliced variable must use precisely the same list of subscripts.Multiple subscript patterns on same variable. See Fix 2.
PFSLRDParfor loop variable {0} is accessed with an invalid combination of sliced indexing expressions and non-indexed reads. It is not valid to access the whole value of a sliced output variable.Sliced write + full read on same variable. See Fix 4.
PFIINThe input variable {0} should be initialized before the PARFOR loop.Variable read before written — pre-allocate before the loop.

Temporary Variable Errors

Variable classified as temporary but used in a way that conflicts.

IDMessageFix pattern
PFUTMPTemporary variable {0} must be set inside the parfor loop before it is used.Ensure first reference in each iteration is a full assignment. See Fix 6.
PFUTVRVariable {0} may have been intended as a reduction variable, but is an uninitialized temporary.Initialise the variable before the parfor (e.g. X = 0;) to enable reduction classification.
PFTUSThe temporary variable {0} is used after the PARFOR loop on line {1}, but its value is not available after the loop.Conditional assignment makes it temporary; restructure as sliced output + post-loop reduction. See Fix 7.
PFTUSWThe temporary variable {0} might be used after the PARFOR loop on line {1}. The value set on this line is not available after the loop.Same as PFTUS (warning variant). See Fix 7.

Sliced Variable — Nested For Rules

These fire when a sliced variable is indexed via an inner for loop variable.

IDMessageFix pattern
PFFRNGWhen indexing a sliced variable with a nested for loop variable, the range of the for loop variable must be a row vector of positive constant numbers or variables.Make the inner loop range a literal or broadcast variable. See Fix 3(c).
PFCTXTWhen indexing a sliced variable with a nested for loop variable, the sliced variable must be inside the for loop that defines the range of the for loop variable.Move the sliced assignment inside the inner for loop, or collect into a temporary first.
PFMLTIWhen indexing a sliced variable with a nested for loop variable, the for loop variable must not be assigned other than by its for statement.Don't reassign the inner loop variable inside the loop body.
PFFSUBIndexing a nested for loop variable is not supported in parfor loops.Don't subscript j(k) — use a separate variable.
PFANONUsing a sliced output variable in an anonymous function is not supported in parfor loops.Never write fh = @() slicedOut(ii) or similar

Reduction Variable Rules

IDMessageFix pattern
PFINCRUsing different reduction functions with the same reduction variable is not supported in parfor loops.Use one reduction operation per variable, or split into multiple variables.
PFRNCParfor reduction variable {0} must be used in the same position in each assignment statement when using non-commutative reduction operations '*', '[,]', or '[;]'.Keep the reduction variable on the same side (left or right) in every assignment.
PFNARSubtracting reduction variable {0} from expressions is not supported in parfor loops.Rewrite as addition: X = X + (-expr) instead of X = expr - X.
PFRFHThe parfor reduction function {0} must either be a function name or a broadcast variable.Don't use an expression as the reduction function — assign it to a variable first.
PFRINThe reduction variable {0} might not be set before the PARFOR loop.Initialise the reduction variable before parfor (e.g. total = 0;).
PFRUSThe reduction variable {0} might not be used after the PARFOR loop.Performance warning — the reduction result is unused. Remove or use it.

Transparency Violations

These are straightforward "don't use X in parfor" — no classification analysis needed. In each case, the prohibited function attempts to modify the workspace of the parfor loop in a non-transparent way - i.e. not in the text of the program.

IDMessage
PFBFNUse of this function is invalid inside a PARFOR loop because it accesses or modifies the workspace in a non-transparent way.
PFEVCEVALIN('caller') and ASSIGNIN('caller') are invalid inside of a PARFOR loop.
PFEVBUsing EVALIN('base') or ASSIGNIN('base') inside a PARFOR loop refers to the worker machines' base workspaces.
PFWHOSUsing "who" or "whos" without "-file" is invalid inside a PARFOR loop because it accesses the workspace in a non-transparent way.
PFNFNested functions cannot be called from within parfor loops.
PFLD'load' must assign to an output variable in parfor loops.
PFSVSAVE cannot be called in a PARFOR loop without the '-fromstruct' option.
PFNACK'narginchk' and 'nargoutchk' cannot be used in parfor loops.
PFNAIO'nargin' and 'nargout' require a function argument in parfor loops.
PFINPT'inputname' is not supported in parfor loops.

Structural Constraints

These are simple constraints on constructs that are illegal inside parfor.

IDMessage
PFBRKbreak statements cannot be used inside a parfor loop.
PFRTNreturn statements cannot be used inside a parfor loop.
PFSPMDspmd statements cannot be used inside parfor loops.
PFPFparfor loops cannot be used inside other parfor loops.
PFFORAAssigning to for loop variables is not supported in parfor loops.
PFVSUBIndexing parfor loop variables is not supported in parfor loops.
PFXSTAssigning to the parfor loop index variable is not supported in parfor loops.
PFANSLP'ans' is not supported as a parfor loop variable.
PFANSNS'ans' is not supported as a for loop variable in parfor loops.
PFRNGThe range of a PARFOR statement must be consecutive integers.
PFRNIThe parfor loop can only use a step size of 1 or -1.
PFVARSParfor loop contains too many variables.

Global and persistent data

Workers operating on the body of parfor have completely separate global and persistent workspaces. Do not use global or persistent with parfor.

IDMessage
PFGLOBGlobal variable declarations are not supported in parfor loops.
PFPERSPersistent variable declarations are not supported in parfor loops.
PFGPAvoid assigning to GLOBAL or PERSISTENT variable {0} inside a PARFOR loop.
PFGVAvoid using GLOBAL variable {0} in a PARFOR loop.

Post-Loop Usage Warnings

IDMessage
PFOUSThe output variable {0} might not be used after the PARFOR loop.
PFUIXThe index variable {0} might be used after the PARFOR loop on line {1}, but it is unavailable after the loop.
PFUIXWThe index variable {0} might be used after the PARFOR loop on line {1}. The value set on this line is not available after the loop.

Broadcast Warning

IDMessage
PFBNSThe entire array or structure {0} is a broadcast variable. This might result in unnecessary communication overhead.

PFBNS is almost always harmless. It is an informational performance hint, not an error. The code is correct and will run fine. Do NOT attempt to "fix" this warning unless the user specifically asks about performance — restructuring code to silence PFBNS often introduces real classification errors (e.g. turning a valid broadcast into a broken sliced variable). The safe response is to acknowledge the warning and explain it has no effect on correctness.


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.

Needs: Needs an MCP server

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/parallel-computing/matlab-diagnose-parfor · 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-diagnose-parfor.zip