8.5: Variables
Any result you wish to keep for a while may be assigned to a variable other than
ans
:
≫ x = pi/7 ≫ cos(x) ≫ y = sin(x)^2+cos(x)^2; ≫ y
A semicolon (;) at the end of the line suppresses printing of the result, as when we calculated \(y\) in the next-to-last line just shown. This feature is especially useful when writing MATLAB programs where intermediate results are not of interest and when working with large matrices.
MATLAB supports the dynamic creation of variables. You can create your own variables by just assigning a value to a variable. For example, type
x
=3.5+4.2
. Then the real variable
x
contains the value
7.7
. Variable names must start with an alphabetical character and be less than nineteen characters long. If you type
x
=-3*4.0
, the content
7.7
is replaced by the value
-12
. Some commands allow you to keep track of all the variables that you have already created in your session. Type
who
or
whos
to get the list and names of the variables currently in memory (
whos
gives more information than
who
). To clear all the variables, type in
clear
. To clear a single variable (or several) from the list, follow the command
clear
by the name of the variable you want to delete or by a list of variable names separated by spaces. Try it now.
MATLAB is case sensitive. In other words, \(x\) and \(X\) are two different variables. You can control the case sensitivity of MATLAB by entering the command
casesen
, which toggles the sensitivity. The command
casesen
on enforces case sensitivity, and
casesenoff
cancels it.
If one line is not enough to enter your command, then finish the first line with two dots (. . ) and continue on the next line. You can enter more than one command per line by separating them with commas if you want the result displayed or with semicolons if you do not want the result displayed. For example, type
≫ theta = pi/7; x = cos(theta); y = sin(theta); ≫ x,y
to first compute
theta
,
cos
(theta)
, and
sin
(theta)
and then to print \(x\) and \(y\).