home / skills / openclaw / skills / matlab

This skill helps you avoid common MATLAB mistakes by highlighting indexing traps, matrix vs element-wise operations, and vectorization pitfalls.

npx playbooks add skill openclaw/skills --skill matlab

Review the files below or copy the command above to add this skill to your agents.

Files (2)
SKILL.md
2.9 KB
---
name: MATLAB
description: Avoid common MATLAB mistakes — indexing traps, matrix vs element-wise ops, and vectorization pitfalls.
metadata: {"clawdbot":{"emoji":"📐","requires":{"bins":["matlab"]},"os":["linux","darwin","win32"]}}
---

## Indexing
- 1-based indexing — first element is `A(1)`, not `A(0)`
- `end` keyword for last index — `A(end)`, `A(end-1)`, works in any dimension
- Linear indexing on matrices — `A(5)` accesses 5th element column-major order
- Logical indexing returns vector — `A(A > 0)` gives 1D result regardless of A's shape

## Matrix vs Element-wise
- `*` is matrix multiplication — `.*` for element-wise
- `/` solves `A*x = B` — `./` for element-wise division
- `^` is matrix power — `.^` for element-wise power
- Forgetting the dot is silent bug — dimensions might accidentally match

## Vector Shape Matters
- Row vector: `[1 2 3]` or `[1, 2, 3]` — shape is 1×3
- Column vector: `[1; 2; 3]` — shape is 3×1
- Transpose with `'` (conjugate) or `.'` (non-conjugate) — for complex, they differ
- `*` between row and column gives scalar or matrix — depending on order

## Array Preallocation
- Growing arrays in loops is slow — preallocate: `A = zeros(1000, 1)`
- `zeros`, `ones`, `nan` for preallocation — specify size upfront
- Cell arrays: `cell(n, m)` — preallocate cells too

## Broadcasting
- Implicit expansion since R2016b — `A + b` works if dimensions compatible
- Singleton dimensions expand — `[1;2;3] + [10 20]` gives 3×2
- Before R2016b needed `bsxfun` — legacy code may still use it

## NaN Handling
- `NaN ~= NaN` is true — use `isnan()` to check
- Most operations propagate NaN — `sum([1 NaN 3])` is NaN
- Use `'omitnan'` flag — `sum(A, 'omitnan')`, `mean(A, 'omitnan')`

## Cell Arrays vs Matrices
- `{}` for cell arrays — hold mixed types, different sizes
- `()` indexing returns cell — `C(1)` is 1×1 cell
- `{}` indexing extracts content — `C{1}` is the actual value
- Comma-separated list from `C{:}` — useful for function arguments

## Common Mistakes
- `=` for assignment, `==` for comparison — `if x = 5` is error in MATLAB
- Semicolon suppresses output — forget it and flood command window
- `clear` removes all variables — use `clearvars` for selective, `close all` for figures
- `i` and `j` are imaginary unit — don't use as loop variables, or reassign explicitly
- String vs char: `"text"` vs `'text'` — double quotes are string arrays (R2017a+)

## Functions
- Anonymous functions: `f = @(x) x^2` — quick inline functions
- Multiple outputs: `[a, b] = func()` — must capture or use `~` to ignore
- `nargin`/`nargout` for optional args — check how many inputs/outputs provided
- `varargin`/`varargout` for variable args — cell array of extra arguments

## Debugging
- `dbstop if error` — breakpoint on any error
- `keyboard` in code pauses execution — enter debug mode at that line
- `whos` shows variable sizes — `size(A)` for specific variable

Overview

This skill helps you avoid common MATLAB mistakes by highlighting indexing pitfalls, matrix vs element-wise operator errors, and vectorization traps. It focuses on practical rules, quick checks, and code patterns that reduce bugs and improve performance. Use it to catch silent dimension mismatches, NaN gotchas, and inefficient loops.

How this skill works

The skill inspects typical MATLAB constructs and points out likely problems: 1-based and linear indexing, the need for dot operators (.* ./ .^) versus matrix operators, and shape mismatches between row and column vectors. It flags slow patterns like growing arrays in loops, suggests preallocation, and recommends correct handling of NaN, cell arrays, and function argument patterns. It also offers debugging tips such as break-on-error and useful introspection commands.

When to use it

  • Writing or reviewing MATLAB scripts that manipulate arrays and matrices
  • Optimizing code that uses loops, to replace with vectorized operations
  • Debugging unexpected outputs due to indexing or operator misuse
  • Converting legacy code that uses bsxfun or pre-R2016b patterns
  • Working with mixed-type data in cell arrays or handling missing values (NaN)

Best practices

  • Always remember MATLAB is 1-based and use end for last indices to avoid off-by-one errors
  • Use element-wise operators (.* ./ .^) when operating on arrays element-by-element
  • Preallocate arrays and cell arrays (zeros, ones, nan, cell) before loops to improve performance
  • Keep track of vector shapes: row vs column matters. Use .' for non-conjugate transpose when working with complex values
  • Check for NaNs with isnan() and use 'omitnan' in aggregation functions when appropriate
  • Prefer clearvars over clear and avoid reassigning i/j if you need the imaginary unit

Example use cases

  • Detecting a silent bug where * was used instead of .* causing accidental matrix multiplication
  • Refactoring a loop that grows a matrix into a preallocated, vectorized form for speed
  • Fixing indexing errors caused by treating MATLAB like a 0-based language or misusing linear indexing on matrices
  • Handling datasets with missing values by switching to sum(A,'omitnan') or using isnan() filters
  • Extracting contents from a cell array with C{:} to pass as function arguments

FAQ

How do I check whether to use * or .*?

If both operands are matrices meant for linear algebra, use *. If you intend element-wise multiplication of same-sized arrays, use .*; silent dimension matches can hide mistakes.

Why is my NaN causing functions to return NaN?

Most operations propagate NaN. Use isnan() to detect them and aggregation options like 'omitnan' to ignore NaNs in summaries.