
Slow Code Is a Diagnosis Problem Before It Is a Coding Problem
Every MATLAB user eventually hits the wall: a script that took seconds starts taking minutes, then hours, and the optimisation folklore begins — convert everything, avoid all loops, buy a bigger machine. Most of that folklore is wasted effort, because slow code is rarely slow everywhere; it is slow at one bottleneck, and the rest of the optimisation is decoration. Learning how to speed up MATLAB code therefore starts with measurement, not rewriting: profile to find the hot lines, fix the three classic structural faults (growing arrays, element-by-element loops where vector operations exist, and recomputation of things that do not change), and re-measure before touching anything else. This guide walks that discipline in order — the profiler and how to read it, preallocation, vectorisation with judgement (including the cases where a loop is genuinely fine), built-in functions and memory habits, and the verification step that keeps “faster” from quietly becoming “different”. It assumes you can already produce correct results, ideally presented properly — the plotting workflow in our guide to how to plot in MATLAB is the natural companion — because speed applied to wrong answers is just arriving at the wrong place sooner.
Profile First: Let the Profiler Choose Your Battle
Run profile on, execute your script, then profile viewer — or use the Code Analyzer and Run-and-Time tools in the editor — and read the table the only way that matters: by total self-time. Sort descending and the truth appears, almost always in an anticlimactic shape: one function, often one loop, consuming 70–90% of the runtime while the rest of the script idles in rounding error. That concentration is the good news; it means optimisation is a sniper task, not a renovation. Note also call counts: a line executed two million times inside nested loops is a different problem from an expensive built-in called twice, and the fix differs accordingly — algorithmic first (can this computation happen once, outside the loop?), structural second (preallocate, vectorise), micro-optimisation last (and usually never). Keep the profile of the original beside every change you make, and time with timeit or repeated tic/toc runs rather than one heroic stopwatch moment: first runs include JIT warm-up and file caching that flatter or punish unfairly, and a “2× speedup” measured once is a rumour, not a result. Write the before/after numbers in a comment at the top of the file; future you, opening this script in eight months, deserves the evidence trail.
Preallocation and Vectorisation: The Two Big Levers
Preallocation fixes the single most common MATLAB crime: growing an array inside a loop (x(i) = ... with no prior x = zeros(1, n)). Each growth forces MATLAB to reallocate and copy the whole array, so the loop’s cost balloons quadratically while the profiler politely points at an innocent assignment line. Declaring the final size upfront — zeros, ones, nan as appropriate — routinely turns minutes into seconds on its own, and it forces a clarifying question (how big is this, actually?) that improves the algorithm too. Vectorisation replaces element-wise loops with whole-array operations: y = sin(x) .* exp(-x) instead of looping over indices, logical indexing (x(x > 0) = 0) instead of if-chains inside loops, and matrix operations instead of nested summation loops. The wins are real — built-ins run compiled, threaded code — but the folklore overreaches in two places. First, a vectorised line that builds a giant intermediate array can lose to a modest loop on memory alone; chunk or loop when the intermediates dwarf RAM. Second, some loops are honest: sequential recurrences where each step depends on the last cannot vectorise, and forcing them wastes days — profile says whether they’re even the bottleneck. Modern MATLAB’s JIT executes many simple loops respectably, which is exactly why measurement outranks folklore: optimise the lines the profiler names, in the order it names them.
When Loops Are Innocent, and the Parallel Temptation
Two judgement calls protect you from the folklore’s worst excesses. First: loops are not the enemy; unexamined loops are. A loop over twelve files, or fifty parameter values, that calls fast built-ins inside costs nothing that matters — the profiler will show its total share at a few percent, and vectorising it buys complexity at a negative exchange rate. Similarly, loops that exist for clarity around a cheap operation are good engineering, not crimes; MATLAB’s JIT handles plain numeric for-loops well enough that “loop = slow” has been half-obsolete for years. Reserve your suspicion for loops with big iteration counts, inner bodies that allocate or grow, and nested loops whose depth multiplies quietly — the profiler distinguishes all of these from their innocent cousins in one glance, which is the whole argument for measuring first. Second: parallel computing is the last resort, not the first. parfor and the Parallel Computing Toolbox genuinely help when iterations are independent and heavy — parameter sweeps and Monte Carlo runs are the textbook cases — but they add licensing cost, debugging pain (breakpoints and printing behave differently), and memory multiplication, since each worker wants its own copies. A script that is 10× faster after preallocation and vectorisation, which covers most real cases, never needed the pool. Reach for parallelism only when the profile shows heavy, independent, irreducible work — and even then, profile the parallel version too, because a badly sliced parfor can run slower than the loop it replaced while consuming eight cores to prove it.
Built-ins, Memory, and Proving You Broke Nothing
The third lever is substitution: replace hand-rolled computations with the built-ins that already do them at compiled speed. Filtering, interpolation, statistics, sorting, searching — movmean instead of a hand-windowed loop, interp1 instead of manual bracketing, accumarray instead of grouped accumulation loops, table and timetable joins instead of row-matching code. The pattern-recognition skill is noticing that your loop is a named operation wearing a disguise. Memory habits matter at scale: work in the smallest adequate type, avoid keeping several full copies of a large array alive simultaneously (clear, reuse, or process in blocks), and remember that pass-by-value semantics make function boundaries cheaper in copies than intuition suggests but not free. Then verify. Every optimisation is a code change, and code changes have a failure mode called “faster and wrong”: keep the original script’s outputs saved, run the new version on the same inputs, and compare with max(abs(a - b)) against a tolerance appropriate to the arithmetic — bit-identical is ideal, explained-tiny is acceptable, unexplained-anything is a stop. Only when the numbers match within tolerance and the profiler confirms the bottleneck moved do you delete the old path. Speed, like the plots it feeds, is an evidence discipline: measure, fix the named fault, re-measure, verify. Do that, and the folklore budget — the bigger machine, the desperate rewrite — usually stays unspent, because the wall was never the machine. It was one loop, growing an array, recomputing constants, two million times — and now it isn’t.
