2.2. Variables and Values¶
Reading Assignment
Please read chapter 1 of Physical Modeling in MATLAB, by Allen B. Downey [DOWNEY11].
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 >>
in the Command Window is a prompt where
commands are given to MATLAB.
>> 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 results and to feed information to future computations. The name given to a variable is called an identifier, which just means that we made up the name. The rules for what is a valid identifier are covered later.
-
Assignment Statement
Storing data in a variable with an equal sign = is formally called an assignment statement in computer science terminology. Some data value is assigned to be held in a variable.
-
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.
Operator | Function |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
^ | Exponent |
The order of operations is what you would expect from basic algebra: multiplication and division happen before addition and subtraction. If you want to override the order of operations, you can use parentheses.
>> 2 * (3-4) / 5
ans =
-0.4000
The following is the order of operations.
- parentheses, brackets
- exponents, roots
- multiplication, division
- addition, subtraction
Caution
A common error for beginning programmers is leaving out the * for multiplication.
2.2.2. Identifier Names¶
A few simple rules govern identifier names for variables and functions.
- Can only contain letters, numbers, and underscores
- Can only start with letters
- Are case-sensitive
- Can be between 1 and 63 characters long
- Can not be one of MATLAB’s keywords
Incorrect | Correct |
---|---|
X-Y | XY |
month&year | monthYear |
1987value | value1987 |
CO2 conc | CO2_conc |
What is a keyword?
Look up the function iskeyword in the MATLAB documentation.
2.2.3. Calling Functions¶
MATLAB has functions for any calculation you can imagine and a lot more.
>> sin(1)
ans =
0.8415
This command is an example of a function call. The name of the function is
sin, which is the usual abbreviation for the trigonometric sine. The value in
parentheses is called the argument. All the trig functions in MATLAB work
in radians, but there is a set of trig function ending with a ‘d’ that use
angles in degrees. These include sind
, cosd
, tand
, etc.
Some functions take more than one argument, in which case they are separated by commas. For example, atan2 computes the inverse tangent, which is the angle in radians between the positive x-axis and the point with the given and coordinates.
>> atan2(1,1)
ans =
0.7854
Caution
A common error is to leave out the commas between the arguments of a function.
2.2.4. Numeric Data Types¶
The default data type for numeric variables is double floating point (64 bits). It supports very large positive or negative numbers and numbers 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 integers 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 (discussed later). Scalar values are thus reported as having a size of 1x1.
>> a = 5 a = 5 >> whos Name Size Bytes Class Attributes a 1x1 8 double
Look it Up!
Look up the documentation for the format command. How can it be applied? What affect does it have on the number of digits of accuracy that MATLAB stores for variables? Note that format compact removes extra blank lines from results displayed in the command window.
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 them in more detail in the Vectors and Matrices in MATLAB section. For now, let us learn how to use a simple array, which MATLAB calls a row vector. Calling it a row vector just means that data is stored in a single row. Consider the following lines of code.
>> 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
The zeros
function was used to create a row vector consisting of one row
and five columns that are filled with zeros. In the next two commands we
used assignment statements to change the values stored in the first and
forth positions. Notice two things about the use of an index number that are
different than most other programming languages. First, we use a pair of
parenthesis around the index number. Secondly, the range of indices goes
from 1 to N, where N is the size of the row vector.
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 open plots when the program starts. Add the line
clear; close all
at the beginning of the program to achieve this.
2.2.7. Some Pre-defined Constants¶
Since MATLAB is primarily used for numerical calculations, there are few math constants that we need to know about. The irrational number is perhaps the most obvious, but MATLAB also includes constants for working with the imaginary part of complex numbers () and even infinity.
Name | Meaning |
---|---|
i | Imaginary unit |
j | Imaginary unit |
Inf | Infinity |
pi | Ratio of circle’s circumference to its diameter |
NaN | Not-a-Number |
You might expect to see the irrational number . Instead, there is a function, exp(x)
, that returns
. The usage of the number 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(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 .
Note
Now, complete the homework assignment Entering Basic Equations using MATLAB Grader.