MA

MATLAB Defaults

Core MATLAB coding conventions covering naming, vectorization, and script organization

Details

Language / Topic
matlabMATLAB
Category
Style Guide

Rules

balanced
- Use `camelCase` for variable and function names (e.g., `sampleRate`, `computeFFT`) and `PascalCase` for class names — avoid single-letter names except loop counters.
- Prefer vectorized operations over `for` loops: `result = A .* B` is faster than iterating element-by-element because MATLAB is optimized for matrix operations.
- Terminate statements with `;` to suppress output in scripts and functions — omitting `;` in long-running computations floods the Command Window and slows execution.
- Use `function [out1, out2] = myFunc(in1, in2)` signatures with named inputs and outputs — never rely on `nargin`/`nargout` for primary API design.
- Pre-allocate arrays with `zeros(m, n)`, `ones(m, n)`, or `NaN(m, n)` before filling in a loop — dynamic resizing inside loops is O(n²) due to repeated reallocation.
- Use `end` keyword for last-index indexing (`A(end)`, `A(2:end)`) instead of computing `length(A)` manually — it is clearer and works for any dimension.
- Prefer `~` as a placeholder for unused output arguments: `[~, idx] = sort(A)` instead of `[ignored, idx] = sort(A)` to avoid lint warnings.
- Use `logical` indexing (`A(A > 0)`) instead of `find` + numeric indexing for element selection — it is more readable and often faster.