Syntax, Statements and Variables

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

The reference material consulted while preparing these pages is listed in the section bibliography.

Written against MATLAB R2026b. The sessions below were run in GNU Octave 11.3.0 (MATLAB code that Octave also accepts) and show Octave’s output, whose layout and some messages differ from MATLAB’s; where the behaviour differs in a way that matters it is said so. Features that Octave does not share (for instance the 2048-character name limit) are checked against the R2026b documentation and labelled "not run here".

MATLAB code is a sequence of statements. Almost everything on this page is something you meet in the first hour, and most of it is simple, but a handful of rules (the semicolon, the space inside brackets, command syntax and shadowed names) explain a large share of the surprising results that beginners and experienced programmers alike report. The workspace that holds the variables is described on Workspace Variables and MAT-Files; the Command Window where statements are typed is on Desktop and Command Window.

Statements and expressions

A statement is either an assignment (x = 3), an expression that is only evaluated (5 + 5), or a call of a function or a keyword construct such as if or for. An expression is built from constants, variables, operators and function calls (see Operators and Precedence).

  • If a statement is not ended with a semicolon, MATLAB prints the result. An assignment prints the variable name and value (x = 3); an expression that is not assigned prints ans = ....

  • A semicolon at the end suppresses the output. The statement still runs and the variable is still set; only the echo is hidden. Suppress the output of anything that is large or inside a loop: printing is slow, and in a script it hides the lines you do want to see.

  • Several statements can share one line if they are separated by a comma (the output is shown) or a semicolon (the output is hidden).

  • An expression that is not assigned to a variable stores its value in the variable ans, which is overwritten by the next such expression. A call that returns nothing (disp, a plot command) does not change ans. Do not rely on ans in a script: assign to a named variable.

x = 3
y = 4;
a = 1, b = 2; c = 3
5 + 5;
ans
s = 1 - 1/2 + 1/3 ...
  - 1/4

Octave 11.3.0 output:

x = 3
a = 1
c = 3
ans = 10
s = 0.5833

y and b are set but not printed because of the semicolons; 5 + 5; is computed silently and ans then shows 10. The last statement continues over two lines (see Continuing a statement).

Comments

A comment starts with a percent sign, %, and runs to the end of the line; it can follow code on the same line. To comment out several lines, put %{ alone on a line before them and %} alone on a line after them; nothing else, not even a space-separated word, may share those two lines. Block comments can be nested. To comment out part of a statement that spans several lines, put an ellipsis in the part to be ignored instead of a percent sign. A line that starts with two percent signs, %%, is a section title in a script (see Scripts and Code Sections). In the Editor the shortcut for commenting a selection is Ctrl+R (uncomment Ctrl+Shift+R); on macOS it is Command+/ and Command+Option+/, and on Linux Ctrl+/ and Ctrl+Shift+/.

% A full-line comment
a = magic(3);
%{
sum(a)
diag(a)
%}
y = sum(a(:))   % a comment after code

Continuing a statement

Three dots, an ellipsis, at the end of a line continue the statement on the next line; the ellipsis and everything after it on that line are ignored, which means that an ellipsis outside quoted text is equivalent to a space. Inside a matrix this is why [1.23... followed by 4.56] is the same as [1.23 4.56]. The start and end quotation marks of a character vector must appear on the same line, so a long text is built by concatenating pieces, each closed on its own line. Inside a double-quoted string the same rule applies; build a long string by joining pieces with + or append. Square brackets do not join strings: ["abc" "def"] is a 1-by-2 string array, not one longer string.

s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ...
  - 1/6 + 1/7 - 1/8 + 1/9;
mytext = ['Accelerating the pace of ' ...
          'engineering and science'];
z = [1 2 ...
     3 4]

Octave 11.3.0 shows z = 1 2 3 4 for the last statement. In an array a newline also separates rows, so a matrix can be written over several lines without any ellipsis (see Matrices and Arrays).

Variable names

A valid variable name starts with an English letter, followed by letters, digits or underscores. MATLAB is case sensitive, so A and a are different variables, and the length of a name is limited to the value namelengthmax returns. That value was 63 characters up to R2024b and is 2048 since R2025a (not run here: Octave 11.3.0 returns 63). Names must not be keywords such as if or end.

  • isvarname(s) tells whether s is a valid variable name (it returns false for a keyword).

  • iskeyword with no argument lists the keywords; iskeyword(s) tests one. In current releases the list contains words such as for, while, if, end, function, return, parfor, spmd, switch, try and classdef; the list is the one iskeyword prints, not one to memorise.

  • matlab.lang.makeValidName(str) turns an arbitrary string into a valid name (used when table variable names come from file headers): '2nd plate' becomes x2ndPlate and 'heat flow' becomes heatFlow.

  • exist(name) and which name tell whether a name is already a variable, function or file before you reuse it.

isvarname('plate2'), isvarname('2plate'), isvarname('end')
iskeyword('end')
namelengthmax
matlab.lang.makeValidName('2nd plate')
matlab.lang.makeValidName('heat flow')

Octave 11.3.0 output:

ans = 1
ans = 0
ans = 0
ans = 1
ans = 63
ans = x2ndPlate
ans = heatFlow

Names that follow the style of the heatflow scenario (nx, ny, dx, alpha, T) are short and lower case, with T for the temperature matrix; avoid names that coincide with functions (size, max, sum, table, path, i, j) because the variable hides the function.

Case and space sensitivity

Case. X and x are two variables, and a function called as Sin is not sin. A wrong capital letter is reported as an undefined variable or function; in Octave 11.3.0, after Plate = 1, the statement plate fails with 'plate' undefined, and MATLAB reports Unrecognized function or variable 'plate'. (identifier MATLAB:UndefinedFunction). Match the case of file names exactly too, because file systems differ in how they treat it.

Spaces. Spaces are mostly ignored, except inside the brackets that build arrays, where a space separates elements and [1 -2] has two elements while [1 - 2] has one. The rule: a space before a sign and none after it starts a new element.

a = 1; b = 2;
[1 - 2]
[1 -2]
[a - b]
[a -b]
[a, -b]

Octave 11.3.0 output:

ans = -1
ans =

   1  -2

ans = -1
ans =

   1  -2

ans =

   1  -2

The same rule means that [a' b'] and [a ' b'] differ (the second starts a string). Put a space on both sides of a binary operator, or on neither, and use commas in matrices when the line is long: it avoids the whole class of mistake.

Command syntax and function syntax

Every function can be called with function syntax, [out1,...,outM] = name(in1,...,inN), where the inputs are values, variables or expressions that MATLAB evaluates first. Many functions can also be called with command syntax, name arg1 arg2, where the arguments are separated by spaces and are always passed as character vectors. The two forms are equivalent for text arguments (this is the command-function duality):

load durer.mat        % command syntax
load('durer.mat')     % function syntax

Command syntax is convenient for commands you type (hold on, format long, clear x, close all, cd folder, whos -file data.mat) and for the -option style of save, load, clear and whos. It has limits:

  • The arguments are always character vectors. disp hello shows hello, but A = 123; disp A shows the letter A, not 123; use disp(A).

  • A command-syntax call cannot return a value into a variable: if the function returns one, it goes into ans. The form x = round 3.499 is an error.

  • A space splits the arguments, so disp hello world passes two arguments and fails (too many inputs; Octave 11.3.0 prints the disp usage). Quote the argument: disp 'hello world', or use disp('hello world').

  • Quotes are passed literally: disp "string" shows "string" including the double quotes as characters, whereas disp("string") shows string.

disp hello
disp('hello')
disp hello world

Octave 11.3.0 output (the third statement is an error: disp accepts one value, and a second argument is a mistake):

hello
hello
Invalid call to disp.  Correct usage is:

 -- disp (X)
 -- STR = disp (X)

How MATLAB decides

When the first word of a statement could be a function or a variable, MATLAB looks at what follows it: an equal sign means assignment; an opening parenthesis straight after the name means a function call; a space after the name but no space after the following operator-like character means command syntax; spaces on both sides of the operator, or none on either side, mean an operation on variables. So ls ./d is a call of ls with the argument ./d, while ls ./ d and ls./d divide the variable ls by d. The Code Analyzer and the Editor do not know the workspace and use only these syntactic rules, which can disagree with what the Command Window does; the documentation recommends avoiding variable names that conflict with common functions, formatting operators consistently, and calling functions with explicit parentheses.

Special values and constants

A few names are built-in functions that return a constant. They are written without parentheses but they are functions, which is why a variable can replace them.

Name Value

pi

The ratio of a circle’s circumference to its diameter, in double precision.

i, j

The imaginary unit, so 3 + 2i, 3 + 2*i and complex(3,2) agree. The forms 2i and 2j are numbers and cannot be shadowed.

eps

The spacing of doubles at 1, 2.2204e-16 (for the double type); eps(x) is the spacing at x.

Inf, -Inf

Positive and negative infinity, the result of 1/0 and of an overflow.

NaN

Not-a-Number, the result of 0/0 or Inf - Inf; it compares unequal to everything, including itself.

ans

The result of the last unassigned expression.

pi = 3;
r = 2*pi
clear pi
r = 2*pi
i = 5;
w = [1+2i, 3*i]
class(Inf), NaN == NaN

Octave 11.3.0 output:

r = 6
r = 6.2832
w =

    1 +  2i   15 +  0i

ans = double
ans = 0

The first r shows the shadowing problem: once pi = 3 exists in the workspace, the function pi is hidden and every later use gets 3. clear pi removes the variable and restores the function. The most frequent real-world version is i or j used as loop counters, after which 3*i in a complex expression is a real number; in code that works with complex numbers write 1i or 1j, which cannot be shadowed, and avoid i and j as variable names. Likewise a variable named size, max, sum, sin, table or path makes later calls of that function fail, usually with a message about indexing or too many input arguments rather than about the name. exist('name') and which name show what a name currently refers to; the order in which MATLAB resolves names is on Function Precedence and Name Resolution.

Display of results

disp(x) shows a value without its name; format long and format short change the number of digits displayed (not stored); fprintf formats output exactly (see Desktop and Command Window for format). The statement x alone, or display(x), prints with the name.

Pitfalls

  • Forgetting the semicolon in a loop floods the Command Window and slows the program. Adding it to a line you wanted to see hides the answer.

  • Shadowing built-in names: pi, i, j, eps, size, sum, max, mean, table, path, error. Use which to check, clear name to repair.

  • [1 -2] versus [1 - 2]: a sign preceded by a space and followed by none starts a new element.

  • Command syntax with variables: disp A, save file A B (names, intended) but disp A (the letter, usually unintended). When you pass a value, use parentheses.

  • ans overwritten by the next unassigned expression; assign results you need.

  • A name that is a keyword (end, for, function) is invalid; the error appears at parse time.

  • Case: Plate and plate.

Where older books differ

Books for MATLAB 6 and 7 describe a 31-character limit on names (namelengthmax was 31 then, 63 for many years, and is 2048 since R2025a), clear all as the standard first line of a script, and the echo/more off idioms for the old Command Window. They also use i and j freely, which is legal but the reason 1i is preferred. Command syntax is described accurately but its use for anything but interactive commands is discouraged in current style guidance.