Tutorial

Valid Identifiers in MATLAB

An identifier, or name, is a string of characters that identifies some entity in a program.

Rules

Valid identifiers in MATLAB:

  • Must start with a letter, followed by a combination of letters, digits and underscores
  • Cannot be a reserved word
  • Their length must be lower than or equal to the value returned by namelengthmax
Table 1. Examples of valid and invalid identifiers in MATLAB.
Valid Invalid
name _name
x2 2x
lastValue end
n_factorial n!
age $age
% Maximum identifier length
maxLength = namelengthmax;

Case sensitiveness

MATLAB is a case-sensitive programming language, so lowercase and uppercase letters are different entities and generate different identifiers.

% These are different variables
myVar = 1; 
MyVar = 2;

Variable: Abstraction of a computer memory cell or collection of cells, characterized by its name, address, value, type, lifetime, and scope [2].

Conflicts

Avoid creating variables with the same name as a function, because variable names take precedence over function names, which can generate unexpected results in certain situations.

A = 1; 
size = [7, 8, 9];
 
% Bug: 'size' is used as a function, but in this context it is a variable
rowsCount = size(A,1);
Variable names that commonly conflict with function names: i, j, mode, char, size, length, path.

Further reading

I recommend the following books to learn more on how identifiers are treated in MATLAB and other programming languages:

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The first chapter explains MATLAB identifiers, reserved words, and other introductory topics.

  2. Concepts of Programming Languages (11th Edition)

    This book covers the fundamental topics of programming languages. Chapter 4 describes what identifiers, reserved words, variables, bindings, and scopes are in programming languages.

I also recommend the following pages in the MATLAB help documentation, and the other tutorials in this series.

doc namelengthmax;
doc isvarname;

Source code

I hope you have understood how identifiers are treated in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.