Like many other computer languages, constants and variables are fundamental language elements. Using variables in MATLAB is more convenient than in other languages: you do not need to declare the data type of a variable; you can create a variable simply by assigning a value to it using an expression.
Constants
MATLAB provides some internal constants, as shown in Table 2-1. These constants define data frequently used in MATLAB applications and programming, such as calculation precision, pi, etc.
Table 2-1: Internal Constants Provided by MATLAB
| Constant | Return Value |
|---|---|
| ans | Default variable name, saves the most recent result. If you don't specify an output variable for an expression, MATLAB automatically saves the result to the ans variable. |
| eps | Floating-point relative precision, the tolerance used by MATLAB for calculations. |
| realmax | The largest floating-point number the computer can represent. |
| realmin | The smallest floating-point number the computer can represent. |
| intmax | Maximum value of integer types. |
| intmin | Minimum value of integer types. |
| flintmax | Largest consecutive integer for floating-point types. |
| pi | Pi (π). |
| i, j | Imaginary unit. |
| inf | Infinite value. Expressions like n/0 (where n is a non-zero real number) generate inf. |
| NaN | Represents "Not a Number". Results from expressions like 0/0 and inf/inf, arithmetic operations involving NaN, and n/0 where n is complex. |
| computer | Computer type. |
| version | MATLAB version string. |
The constants listed in Table 2-1 can be used directly in MATLAB programming without declaration.
[Example 2-1] Enter some command lines with constants in the Command Window and observe the calculation results.
a = abs(3+4i)
a =
5
z = sqrt(besselk(4/3,rho-i))
z =
0.3730 + 0.3214i
huge = exp(log(realmax))
huge =
1.7977e+308
toobig = pi*huge
toobig =
Inf
Variables
1. Variable Names
The first character of a MATLAB variable name must be a letter, followed by any combination of letters, digits, and underscores.
Note: Variable names in MATLAB are case-sensitive, so A and a are different variables.
Although there is no limit to the length of a variable name, MATLAB only uses the first N characters of the variable name, ignoring the rest. Here, N is the return value of the function namelengthmax. Therefore, it is important to make the first N characters of the variable name unique so that MATLAB can distinguish between different variables.
N = namelengthmax
N =
63
You can use the isvarname function to confirm the validity of a variable name. If the variable name is valid, the function returns 1; otherwise, it returns 0.
[Example 2-2] Enter the following in the Command Window:
isvarname 8th_column
ans =
0
Since the first character of the variable name above is 8, which is invalid, it returns 0.
Note: MATLAB uses the characters i and j to represent the imaginary unit. If you are involved in complex number calculations, you should avoid using i and j as variable names.
MATLAB reserves some keywords and does not allow them to be called. If they are used in a call, it may result in error messages like the following:
Error: Expected a variable, function, or constant, found "=".
Error: "End of Input" expected, "case" found.
Error: Missing operator, comma, or semicolon.
Error: "identifier" expected, "=" found.
Use the iskeyword function without input variables to list all reserved keywords.
2. Creating Variables
Creating variables in MATLAB is simple: you do not need to declare the data type of the variable.
[Example 2-3] Enter the following command line in the Command Window to create a variable A:
A=9
A =
9
Note: Before assigning the value of a variable to another variable, you must ensure that the variable on the right side of the equation has a value; otherwise, an error will be returned. For example, in the following statement, variable a has no value.
A=a
Undefined function or variable 'a'.
If a variable already exists, assigning a value to it will replace its current value.
3. Data Types of Variables
MATLAB provides more than ten types of data, as shown in Figure 2-1. However, all MATLAB variables, regardless of their type, are stored in the form of arrays or matrices. A matrix is the two-dimensional version of an array.
Figure 2-1: Data Types Provided by MATLAB
Table 2-2 summarizes the various data types in MATLAB.
Table 2-2: Data Types in MATLAB
| Data Type | Example | Description |
|---|---|---|
| Logical Array | magic(4) > 10 | Can only contain 1, 0, or true/false. Any non-zero value is converted to 1. |
| Character Array | 'Hello' | Each character is 16 bits long. This array is a string. |
| int8, uint8, int16, uint16, int32, uint32, int64, uint64 | uint8(magic(3)) |
Signed and unsigned integer arrays of lengths 8, 16, 32, and 64 bits. Can be used for integer operations when memory is sufficient. |
| single | 3*10^38 | Single-precision numeric array. Single-precision data requires less storage than double-precision but has slightly lower precision. |
| double | 3*10^300 5+6i | Double-precision numeric array, the most commonly used variable type in MATLAB. |
| Date and Time | t = datetime('now') | Efficient date and time calculation, comparison, and formatted display. |
| Categorical Array | s = categorical({'大';'小';'大';'中';'小'}) 1 | Qualitative data array whose values are taken from a finite set of discrete, non-numeric types. |
| Table | See Section 2.7 | A table consists of several row variables and several column variables. Each variable in a table can have a different data type and size. |
| Timetable | See Section 2.8 | Data in tabular form with timestamps. |
| Cell Array | {17 'hello' eye(2)} | The elements of a cell array contain other arrays. It can centralize related data and information of different sizes. |
| Structure Array | a.day = 12; a.color = 'Red'; a.mat = magic(3); | Structure arrays have field names. These fields contain other arrays. Similar to cell arrays, structure arrays also centralize related data and information. |
| Function Handle | @humps | Handle to a MATLAB function. Function handles can be passed in variable lists and evaluated using the feval function. |
| Map Container Class | Objects that contain keys used for indexing values; keys are not necessarily integers. | |
| Time Series Class | Create and combine time series objects. | |
| Custom Class | inline('sin(x)') |
MATLAB class. This custom class is created using MATLAB functions. |
| Java Class | java.awt.Frame | Java class. You can use existing classes defined by the Java API or third parties, or create your own classes using the Java language. |
In MATLAB, when performing numerical calculations, all variables default to the double type. Use the format command to set the output format of variables.
[Example 2-4] Enter the following command line in the Command Window to create the variable VarFormat:
VarFormat=10.1892
VarFormat =
10.1892
To output the variable value in a 15-digit fixed-point format, enter in the command line:
format long
VarFormat
Returns:
VarFormat =
10.189200000000000
To output the variable value in a 15-digit floating-point format, enter in the command line:
format long e
VarFormat
Returns:
VarFormat =
1.018920000000000e+01
To output the variable value in hexadecimal, enter in the command line:
format hex
VarFormat
Returns the variable value:
VarFormat =
402460ded288ce70