8.3. MATLAB Variables#
A variable is a portion of memory uses to store a value. A variable is referred to by its variable name which can be a short one character name, e.g., x
or y
, or a longer more descriptive name, e.g., student_ID
or first_name
.
Lets declare a variable and assign a value to it. In the console enter the following and press the enter key.
>> a = 2
a =
2
Here MATLAB has stored the value of 2 into the memory which can be accessed using the variable name a
.
8.3.1. Suppressing output#
You may have noticed that MATLAB always returns the value of a command by default. To suppress this use a semi-colon ;
at the end of the line. This is useful for programs that include multiple commands. To demonstrate this enter the following code into the command window.
>> a = 2;
>>
Here we have assigned the value to 2 to the variable a
but because we’ve used a semi-colon MATLAB has not returned the value. To return the value enter the following into the command window.
>> a
a =
2
Lets use variables to calculate the area of a rectangle. Enter the following into the console.
>> width = 4;
>> height = 3;
>> area_of_rectangle = width * height;
>> area_of_rectangle
area_of_rectangle =
12
Here we have created two variables width
and height
to store the width and height of a rectangle. We then create a third variable area_of_rectangle
which stores the area of the rectangle calculated using the values stored in the other two variables. We then retrieve the area of the rectangle.
8.3.2. Variable names#
The choice of variable name is up to us but it must satisfy the following rules:
a variable name must start with a letter or the underscore (
_
) charactera variable name can only contain alpha-numeric characters and underscores (
a
-z
,A
-Z
and_
)a variable name is case sensitive, i.e.,
age
,Age
andAGE
are three different variablesa variable name cannot by any of the MATLAB keywords
Important
Care must be taken when choosing variable names not to use a name already used by MATLAB. For example, if we use a variable name max
then we will not by able to use the max()
function since this will have been overwritten by our variable.
It is good practice to use variable names that are descriptive of what the variable represents, e.g., using length
for the length is easier to read and understand then l
(try to avoid lowercase l
are its easy to confuse then with the characters 1
and I
). The use of underscores _
in place of spaces in variable names is known as pothole case or snake case is common in MATLAB as it makes code easier to read.
8.3.3. Exercise#
The following formula converts a temperature from degree Fahrenheit to degrees Centigrade
Using appropriate variable names, convert the following temperatures from degrees Fahrenheit to degrees centigrade:
37.8\(^\circ\)C
100\(^\circ\)C
\(-\)40\(^\circ\)C