Lesson 2.1

Variables and Naming Rules


  • Learn the programming concept of a variable.
  • Understand the rules MATLAB has for choosing a variable name.
  • Grasp the guidelines for better variable naming.

What Is a Variable?

A mathematical variable is a number that we don’t know yet and may have to solve for. For example, in the simple algebraic equation 2 + x = 3, the mathematical variable is x. A mathematical variable can also essentially be a placeholder for substituting a variety/range of numbers. For example, we can substitute any range of numbers into x in the function f(x) = x + 5 to find the value of a function, f(x). In a general sense, a variable varies its value. A variable’s value may be arbitrary, not specified, or even unknown.

In computer programming, such as MATLAB, a programming variable it is a connection between the variable’s name and a specific storage location in the computer’s memory. For example, the variable X references/points to its allocated storage, which contains some information about the variable like the value you assigned to it. Figure 1 shows a simple graphical illustration of this concept.

Figure 1: A simple visual representation of how variables are saved and called.

Although a variable in computer programming can be used as a mathematical variable, it can also be used for many more applications such as substitution, information storage, iteration, value comparison, and much more. Don’t worry if you are not sure how to do any of these in MATLAB, subsequent lessons will explain how to use variables for all of these things.

Variable Naming Rules in MATLAB

The following four variable naming rules are strictly enforced. If these four rules are not followed, MATLAB will throw errors and the program will not run. Note that the variable naming rules are the same for m-file naming rules (See Lesson XXXXX).

  1. A variable cannot begin with a number (examples: 5VDC, 3rdSensor).
  2. A variable cannot contain a special character (%,&, @, etc.) (examples: var%, time@).
  3. A variable cannot contain any spaces (examples: force Out, voltage signal).
  4. A variable should not be the same name as a predefined MATLAB function (examples: mean(), plot(), char()). Using a predefined function as a variable name will not always return an error, so beware!

Benefits of Good Variable Naming Practices

Given that you stay within naming rules, you are free to use any variable name you wish from “MATLAB’s” perspective. However, just because you can choose any variable name does not necessarily mean you should. Good variable names are essential to writing efficient and understandable code. Choosing your variable names wisely can have the following benefits:

  1. Readability and clarity - It is easier to follow and understand programming code when proper variable naming techniques are followed.
  2. Debugging - For more lengthy programming scripts, debugging (or troubleshooting) of code becomes more efficient.
  3. Collaboration - If you are working with someone on a piece of code, or if someone needs to read and understand your code, it is important to name your variables in a clear way. That someone could also be you five years from now trying to figure out or reuse your code.

MATLAB Variable Naming Guidelines

This section contains a more explicit set of guidelines for naming your variables in MATLAB. These are strongly recommended; however, MATLAB will not throw any errors if these are not followed. Failing to follow good naming conventions, though, can make looking at a simple program seem intimidating and frustrating. Also note that different computer programming languages may have different naming conventions.

  1. A variable covering a large scope (used across a wide range of the program), should have more specific and meaningful names.
    • Good: voltageDrop, pullForce, outputTemperature
    • Bad: vd, forP, To

  2. A variable covering a small scope (used across a short range of the program) should have short, disposable names. This guideline generally applies to loop counters or dummy variables.
    • Good: i, j, elem
    • Bad: looponeiteration, temporaryVariable10

  3. Use CamelCase with leading lower case letters. Note the use of underscores between words (e.g., box_height = 5) is also common; however, CamelCase will be used throughout our MATLAB lessons.
    • Good: pressureSensorOutput, boxHeight, width
    • Bad: pressuresensoroutput, Boxheight, WiDtH

  4. Avoid negating boolean (value of true or false) variable names (no double negatives). The concept of boolean variables will be covered in a subsequent lesson.
    • Good: isGood, isMax, error
    • Bad: isNotGood, isNotMax, noError

  5. Do not make the variable name very long. There is no definite number of characters a variable name should not exceed, so you will have to use your own judgement. In general, it must be long enough to be descriptive, yet short enough to be memorable and useful.
    • Good: avgPartStress, isTankLightOn
    • Bad: averageStressInPartThatIsConnectedToTheOtherPart

The following example shows a short MATLAB script with badly selected variable names. For this example do not worry about the function of this specific MATLAB m-file script. We have included examples and explanations for each guideline to elucidate each point more clearly and hopefully impress them on your memory.

Example 1: Illustrations of Bad Variable Naming
% GUIDELINE 1 %Explanation: Looking at these calculations, it becomes hard to keep track % of what each variable means since the names are not descriptive. a = 2; z = 5/a; r = 8; q = z*r; % GUIDELINE 2 %Explanation: Although you do not know what for loops are (covered in % Chapter 6), this is one of the most common examples for a "short scope". % The variable name "iterationvar7" makes the code messy due to its % unnecessary length. for iterationvar7 = 1:5 iterationResult = iterationvar7*a + iterationvar7; end % GUIDELINE 3 %Explanation: This makes the program harder to read because there is no discernible marker between % words. pressuresensoroutput = 5.5; % GUIDELINE 4 %Explanation: It is unclear exactly what is true. Is it good or not? Is it % max or not? isNotGood = true; isNotMax = false; % GUIDELINE 5 %Explanation: Having very long variable names also makes the code difficult to read even if other % guidelines, like CamelCase, are followed. Additionally, variable names that are this % long are rarely necessary for description and can usually be shortened. voltageReadingFromSecondSensor = 10; MAXimumnumberofreadings = 20; %this violates both guidelines 3 and 5 and compounds the problem [Try this code yourself with Octave Online! Click Here]

In example 2, we rewrite our first MATLAB script example to put our guidelines into practice. Again, for this example do not worry about the function or meaning of this specific MATLAB m-file script. Note that the added white space and alignment further enhance readability.

Example 2: Illustrations of Good Variable Naming
%Note: We feel that the good variable names in this example should be obviously better and do not % require further explanations beyond what we have already given. % GUIDELINE 1 scale = 2; % GUIDELINE 2 for reading = 1:5 readingResult = reading*scale + reading end % GUIDELINE 3 pressureSensorOutput = 5.5; % GUIDELINE 4 isSensorGood = true; isVoltMax = false; % GUIDELINE 5 voltageReadingSensor2 = 10; %Note, this could be further abbreviated to the following depending on your preference voltReadSensor2 = 10; [Try this code yourself with Octave Online! Click Here]

Next Lesson

In the next lesson, we will discover how to store text in a variable.