Anatomy of a MATLAB file
MATLAB is a high-performance language for technical computing, integrating computation, visualization, and programming in an easy-to-use environment.
File extensions: .m
Every part of the example below is labelled and explained. This page is one of 55 annotated tours on AnatomyOf, a free, open-source project by LunarWerx Studios.
What is inside a MATLAB file
Comment
Single-line (%) or block (%{ ... %}), ignored by the interpreter.
A % marks the rest of a line as a comment. For longer explanations, a block comment opens with %{ and closes with %}, each delimiter alone on its own line, and everything between is ignored regardless of length. A comment placed immediately after function on the next line or two doubles as the entry for MATLAB's help command: typing help analyzeData at the prompt prints that leading comment block, so many files treat it as informal documentation rather than just an aside.
Function Definition (Main)
Declares the primary function; the file name must match.
A script file that begins with function is a function file, and MATLAB requires the file name (analyzeData.m) to match the function name exactly, call the file anything else and MATLAB either refuses to find it or silently runs the wrong thing. This is different from most languages, where the file name is cosmetic. Older MATLAB versions required exactly one function per file (with local functions as the exception covered below); modern MATLAB relaxed this so scripts can define multiple functions too, but the one-file-one-name rule for the primary function still holds.
Input/Output Arguments
Variables passed into and returned by the function.
Inputs are listed in parentheses after the function name; outputs are listed in brackets before the =. A function can define more outputs than a caller actually asks for. MATLAB tracks how many were requested via nargout, and unrequested outputs are simply never computed if the code checks for that. Unlike languages with a single return value, [output1, output2] = analyzeData(input1, input2) is ordinary syntax, not tuple-unpacking bolted on afterward. Multiple return values have been part of MATLAB since its earliest versions, reflecting its numerical-computing roots where a function commonly
Section Break (%%)
Divides code into executable sections for publishing/running.
A comment line starting with %% marks a "code section" boundary. The Live Editor and desktop MATLAB editor recognize these and let you run just the section the cursor sits in (Ctrl+Enter) rather than the whole file, which is invaluable for iterating on a long analysis without re-running expensive earlier steps. Sections also structure publish() output: each %%-delimited chunk becomes its own block in the generated HTML/PDF report, with the comment text on the same line rendered as that block's heading.
Variable Assignment & Matrix
Defines variables and matrices using [].
MATLAB (MATrix LABoratory) treats every value as a matrix; a scalar is just a 1-by-1 matrix. Square brackets build one literally: commas or spaces separate elements within a row, semicolons start a new row, so [1, 2, 3; 4, 5, 6; 7, 8, 9] is a 3-by-3 matrix. A trailing semicolon on the statement suppresses echoing the result to the command window; leaving it off is a common debugging trick since MATLAB will print the variable's name and value immediately, no disp required.
Control Flow (Conditional)
Executes code based on conditions (if, elseif, else).
if/elseif/else blocks are closed with a matching end, not indentation or braces. Indentation in MATLAB is purely cosmetic (the editor auto-indents it, but the parser does not care). Conditions are typically scalar logical expressions; if you hand if a non-scalar array it is only true when *every* element is nonzero, which surprises newcomers coming from element-wise languages. disp(...) prints a value without echoing the variable name, making it the go-to for user-facing status messages inside conditionals, as opposed to leaving a bare unsuppressed expression to auto-print.
Control Flow (Loop)
Executes code repeatedly (for, while).
for i = 1:length(processedData) iterates i over each value of the range 1:length(...), and (like every block in MATLAB) the loop is terminated with end rather than a closing brace. Ranges use start:stop (step 1 implied) or start:step:stop, and are themselves ordinary row-vector values you can inspect or reuse. Because MATLAB is built around whole-array operations, an explicit for looping over individual elements is often a sign the same work could be "vectorized" into a single matrix expression instead. Vectorized code is idiomatic and usually faster, so seasoned MATLAB developers reach for lo
Matrix Operation
Efficient mathematical operations on whole matrices.
Bare arithmetic operators default to linear-algebra semantics: * is matrix multiplication and / is matrix right-division, not element-by-element. Prefixing with a dot (.*, ./, .^) switches to element-wise operation, and mixing the two up is one of the most common bugs for anyone new to the language. dataMatrix * scaleFactor + input2 multiplies every element of the matrix by the scalar scaleFactor (scalar-times-matrix is always element-wise regardless of the operator) and adds input2, which MATLAB broadcasts across the matrix if the shapes are compatible.
Plotting Command
Built-in functions for creating visualizations.
figure opens a new figure window, plot(processedData) draws the data on it, and title(...) labels it: no import or plotting library setup required, since visualization is a first-class, built-in part of the language. Calling plot again without a new figure normally overwrites the current axes unless hold on is used first. This batteries-included graphics stack is one of MATLAB's signature conveniences for technical computing: a scientist can go from a raw matrix to a labeled, publication-ready chart in three lines, which is exactly what this snippet does.
Local Function Definition
Helper function visible only within this file.
A function file may define additional function blocks after the primary one; these "local functions" are callable from anywhere else in the same file but are invisible to any other file, giving you private helpers without a separate namespace mechanism. They still each end with their own end. calculateMean here is a small local function like this: it takes a vector, sums it, divides by its length, and returns the mean: utility logic factored out of the main function purely for readability, with no risk of colliding with a same-named function elsewhere in a larger project.
Official MATLAB site · All languages on AnatomyOf
The interactive tour needs JavaScript. Enable it to hover a callout and trace it into the code.