2.2. Variables and Values

As with math equations, we use variables in computer programs. They allow us to associate a storage location in the computer’s memory with a name. We use the variable name to store and retrieve values from the storage location.

2.2.1. Command Window Calculator

The characters >> are the prompt in the Command Window where commands are entered.

>> 2 + 1
ans =
    3

We can save a result to a variable for future reference:

>> x = 2 + 1
x =
    3

Tip

The keyboard arrow keys may be used to retrieve previously entered commands.

Variable

When a value is given a name, it becomes a variable. Variables are used to store data for display or future computations. The name given to a variable is called an identifier, which means that we choose the name. The rules for what is a valid identifier are covered later in Identifier Names.

Assignment Statement

Storing data in a variable with an equal sign (=) is formally called an assignment statement in computer science terminology.

ans
MATLAB knows that users might perform a calculation without saving the result to a variable, but later want to use the result. So any result not saved to a variable is automatically stored in a variable called ans.
NOTE: Only the most recent unsaved result is saved in ans.

The mathematical operators used with simple variables and constant numbers are:

Table 2.1 Math Operators

Operator

Function

+

Addition

-

Subtraction

*

Multiplication

/

Division

^

Exponent

The order of operator precedence is what you would expect from algebra.

  1. parentheses, brackets

  2. exponents, roots

  3. multiplication, division

  4. addition, subtraction

When operations are at the same level, then the order of execution is left to right.

>> 2 * (3-4) / 5
ans =
    -0.4000

2.2.2. Identifier Names

A few simple rules govern the allowed names (called identifiers) for variables and functions. The following table shows examples of common mistakes in choosing identifiers and how they might be corrected.

  • Identifiers can only contain letters, numbers, and underscores.

  • Identifiers can only start with letters.

  • Identifiers are case-sensitive.

  • Identifiers can be between 1 and 63 characters long.

  • Identifiers can not be one of MATLAB’s keywords.

    Table 2.2 Incorrect and Corrected Identifiers

    Incorrect

    Problem

    Correct

    X-Y

    - not allowed

    XY

    month&year

    & not allowed

    monthYear

    1987value

    begins with a number

    value1987

    CO2 conc

    space character not allowed

    CO2_conc

2.2.3. Calling Functions

MATLAB has functions for any calculation you can imagine and much more.

>> sin(1)
ans =
    0.8415

The sin(1) command is an example of a function call. The name of the function is sin, the usual abbreviation for the trigonometric sine. The value in parentheses is called the argument. All the trigonometry functions in MATLAB work in radians, but a set of trigonometry functions ending with a d use degrees. These include sind, cosd, tand, etc.

Some functions take more than one argument, in which case commas separate them. For example, atan2 computes the inverse tangent, which is the angle in radians between the positive \(x\) axis and the point with the given \(y\) and \(x\) coordinates.

>> atan2(1,1)
ans =
    0.7854

2.2.4. Numeric Data Types

The default data type for numeric variables is double precision floating point (64 bits). It supports very large positive or negative numbers and numbers that are very close to zero.

>> big1 = 9.578942e50
big1 =
     9.5789e+50
>> small = 1.07124e-122
small =
      1.0712e-122

Other numeric data types, such as signed and unsigned integers, are available if needed. Look up the documentation for the cast function for a detailed list of data types.

MATLAB treats all numeric data as a matrix. Scalar values are thus reported as having a size of \(1{\times}1\).

>> a = 5
a =
    5
>> whos
Name      Size            Bytes  Class     Attributes

a         1x1                 8  double

2.2.5. Simple Arrays

We use arrays to hold a list of values. Arrays and matrices are central to using MATLAB. We will discuss arrays in more detail in

Vectors and Matrices in MATLAB. For now, let us learn how to use a simple array, which MATLAB calls a row vector. Calling it a row vector means data is stored in a single row.

In the following code example, the zeros(1, 5) function call creates a row vector consisting of one row and five columns filled with zeros. In the next two commands, assignment statements change the values stored in the first and fourth positions. Notice two things about using an index number that are different from most other programming languages. First, we use a pair of parentheses around the index number. Secondly, the indices are from 1 to N, where N is the size of the row vector.

>> x = zeros(1, 5)
x =
    0     0     0     0     0
>> x(1) = 3
x =
    3     0     0     0     0
>> x(4) = 6
x =
    3     0     0     6     0
>> x(1)
ans =
    3

2.2.6. Clearing Variables

The clear command removes all variables from the Workspace. Specific variables may also be removed:

>> clear x

In some cases, it may be desirable, particularly while developing a program, to clear all variables and close any open plots when the program starts. Commands clear; close all achieve this.

2.2.7. Some Pre-defined Constants

Since MATLAB is primarily used for numerical calculations, there are a few math constants that we need to know about. The irrational number \(\pi\) is perhaps the most obvious, but MATLAB also includes constants for working with the imaginary part of complex numbers (\(\sqrt{-1}\)) and even infinity.

Table 2.3 Math Constants

Name

Meaning

i

Imaginary number

j

Imaginary number

Inf

Infinity

pi

Ratio of circle’s circumference to its diameter

NaN

Not-a-Number

You might expect to see the irrational number \(e \approx 2.718281828459046\). Instead, there is a function, exp(x), that returns \(e^x\). The usage of the number \(e\) almost always involves an exponent. If the exponent were always a real number, then an expression such as e^x would suffice, but the exponent may be a complex number. Thus, a function gives the flexibility needed.

>> exp(1)
ans =
    2.7183
>> exp(i*pi)
ans =
  -1.0000 + 0.0000i
>> exp(i*pi/2)
ans =
   0.0000 + 1.0000i

The complex exponent demonstrates Euler’s formula for complex exponentials: \(e^{i\,x} = \cos x + i\,\sin x\) ( Euler’s Complex Exponential Equation).