Lab 1: Matlab
Lab 1: Matlab
Lab 1: Matlab
The scalar is 1 × 1, the column vector is 3 × 1 (3 rows by 1 column), the row vector is 1 ×
4 (1 row by 4 columns), and the matrix is 3 × 3. All the values stored in these matrices are
stored in what are called elements.
MATLAB is written to work with matrices; the name MATLAB is short for “matrix
laboratory.” For this reason, it is very easy to create vector and matrix variables, and there
are many operations and functions that can be used on vectors and matrices.
A vector in MATLAB is equivalent to what is called a one-dimensional array in other
languages. A matrix is equivalent to a two-dimensional array. Usually, even in MATLAB,
some operations that can be performed on either vectors or matrices are referred to as array
operations. The term array also frequently is used to mean generically either a vector or
a matrix.
1.3.1. Creating row Vectors
There are several ways to create row vector variables. The most direct way is to put the
values that you want in the vector in square brackets, separated by either spaces or commas.
For example, both of these assignment statements create the same vector v:
>> v = [1 2 3 4]
v=
1234
>> v = [1,2,3,4]
v=
1234
Both of these create a row vector variable that has four elements; each value is stored in a
separate element in the vector.
If, as in the earlier examples, the values in the vector are regularly spaced, the colon
operator can be used to iterate through these values. For example, 1:5 results in all the
integers from 1 to 5:
>> vec = 1:5
vec =
12345
Note that in this case, the brackets [ ] are not necessary to define the vector.
With the colon operator, a step value can also be specified with another colon, in the form
(first:step:last). For example, to create a vector with all integers from 1 to 9 in steps of 2:
>> nv = 1:2:9
nv =
13579
Similarly, the linspace function creates a linearly spaced vector; linspace(x,y,n) creates a
vector with n values in the inclusive range from x to y. For example, the following creates
a vector with five values linearly spaced between 3 and 15, including the 3 and 15:
>> ls = linspace(3,15,5)
ls =
3 6 9 12 15
Vector variables can also be created using existing variables. For example, a new vector is
created here consisting first of all the values from nv followed by all values from ls:
>> newvec = [nv ls]
newvec =
1 3 5 7 9 3 6 9 12 15
Putting two vectors together like this to create a new one is called concatenating the
vectors.
1.3.2 Creating Column Vectors
One way to create a column vector is by explicitly putting the values in square brackets,
separated by semicolons:
>> c = [1; 2; 3; 4]
c=
1
2
3
4
There is no direct way to use the colon operator described earlier to get a column vector.
However, any row vector created using any of these methods can be transposed to get a
column vector. In general, the transpose of a matrix is a new matrix in which the rows and
columns are interchanged. For vectors, transposing a row vector results in a column vector,
and transposing a column vector results in a row vector. MATLAB has a built-in operator,
the apostrophe, to get a transpose.
>> r = 1:3;
>> c = r’
c=
1
2
3
1.3.3. Creating Matrix Variables
Creating a matrix variable is really just a generalization of creating row and column vector
variables. That is, the values within a row are separated by either spaces or commas, and
the different rows are separated by semicolons. For example, the matrix variable mat is
created by explicitly typing values:
>> mat = [4 3 1; 2 5 6]
mat =
4 3 1
2 5 6
There must always be the same number of values in each row. If you attempt to create a
matrix in which there are different numbers of values in the rows, the result will be an error
message; for example:
>> mat = [3 5 7; 1 2]
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.
Iterators can also be used for the values on the rows using the colon operator; for example:
>> mat = [2:4; 3:5]
mat =
2 3 4
3 4 5
Different rows in the matrix can also be specified by pressing the Enter key after each row
instead of typing a semicolon when entering the matrix values; for example:
>> newmat = [2 6 88
33 5 2]
newmat =
2 6 88
33 5 2
Matrices of random numbers can be created using the rand and randint functions. The first
two arguments to the randint function specify the size of the matrix of random integers.
For example, the following will create a 2 × 4 matrix of random integers, each in the range
from 10 to 30:
>> randint(2,4,[10,30])
ans =
29 22 28 19
14 20 26 10
For the rand function, if a single value n is passed to it, an n × n matrix will be created, or
passing two arguments will specify the number of rows and columns:
>> rand(2)
ans =
0.2311 0.4860
0.6068 0.8913
>> rand(1,3)
ans =
0.7621 0.4565 0.0185
MATLAB also has several functions that create special matrices. For example, the zeros
function creates a matrix of all zeros. Like rand, either one argument can be passed (which
will be both the number of rows and columns), or two arguments (first the number of rows
and then the number of columns).
>> zeros(3)
ans =
0 0 0
0 0 0
0 0 0
>> zeros(2,4)
ans =
0 0 0 0
0 0 0 0
Exercises 1: Create a variable ftemp to store a temperature in degrees Fahrenheit (F).
Convert this to degrees Celsius and store the result in a variable ctemp. The conversion
factor is C = (F – 32) * 5/9.
Exercises 2: Using the colon operator, create the following vectors
3 4 5 6
1.0000 1.5000 2.0000 2.5000 3.0000
5 4 3 2
Exercises 3: Using the linspace function, create the following vectors:
4 6 8
–3 –6 –9 –12 –15
9 7 5
Exercises 4: Using colon operators for the rows, create the matrix:
7 6 5
3 5 7
1.4. Matlab scripts
A script is a sequence of MATLAB instructions that is stored in a file and saved. The
contents of a script can be displayed in the Command Window using the type command.
The script can be executed, or run, by simply entering the name of the file (without the .m
extension).
To create a script, click File, then New, then M-file. A new window will appear called the
Editor. To create a new script, simply type the sequence of statements (notice that line
numbers will appear on the left).
When finished, save the file using File and then Save. Make sure that the extension .m is
on the filename (this should be the default). The rules for filenames are the same as for
variables (they must start with a letter, after that there can be letters, digits, or the
underscore, etc.). By default, scripts will be saved in the Work Directory. If you want to
save the file in a different directory, the Current Directory can be changed.
For example, we will now create a script called script1.m that calculates the area of a circle.
It assigns a value for the radius, and then calculates the area based on that radius.
In this text, scripts will be displayed in a box with the name on top.
script1.m
radius = 5
area = pi * (radius^2)
In the Command Window, the contents of the script can be displayed, and the script can be
executed. The type command shows the contents of the file named script1.m (notice that
the .m is not included):
>> type script1
radius = 5
area = pi * (radius^2)
There are two ways to view a script once it has been written: either open the Editor Window
to view it, or use the type command as shown here to display it in the Command Window.
To actually run or execute the script, the name of the file is entered at the prompt (again,
without the .m). When executed, the results of the two assignment statements are displayed,
since the output was not suppressed for either statement.
>> script1
radius =
5
area =
78.5398
Once the script has been executed, you may find that you want to make changes to it
(especially if there are errors!). To edit an existing file, there are several methods to open
it. The easiest are:
Click File, then Open, then click the name of the file.
Click the Current Directory tab (if it is not already shown), then doubleclick the
name of the file.
It is very important that all scripts be documented well, so that people can understand what
the script does and how it accomplishes that. One way of documenting a script is to put
comments in it. In MATLAB, a comment is anything from a % to the end of that particular
line. Comments are completely ignored when the script is executed. To put in a comment,
simply type the % symbol at the beginning of a line, or select the comment lines and then
click Text and then Comment and the Editor will put in the % symbols for you.
1.5. Plot and Subplot
The MATLAB command plot allows you to graphically display vector data (in our case
here, the two signals). For example, if you had the variables t for time, and y for the signal,
typing the command plot(t, y); will display a plot of t vs. y. See help plot for more
information. Annotating your plots is very IMPORTANT! Here are a few annotation
commands.
• title('Here is a title'); - Adds the text "Here is a title" to the top of the plot.
• xlabel('Control Voltage (mV)'); - Adds text to the X-axis.
• ylabel('Current (mA)'); - Adds text to the Y-axis.
• grid on; - Adds a grid to the plot.
In order to display multiple plots in one window you must use the subplot command. This
command takes three arguments, subplot(m, n, p) . The first two breaks the window into a
m by n matrix of smaller plot windows. The third argument, p, selects which plot is active.
For example, if we have three signals x, y, and z, that we want to plot against time, t, then
we can use the subplot command to produce a single window with three plots stacked on
top of each other.
subplot(3,1,1);
plot(t,x);
subplot(3,1,2);
plot(t,y);
subplot(3,1,3);
plot(t,z);
Exercises 5: Plot exp(x) for values of x ranging from –2 to 2 in steps of 0.1. Put an
appropriate title on the plot, and label the axes.
Exercises 6: Plot sin (x) for x values ranging from 0 to (in separate Figure Windows):
using 10 points in this range
using 100 points in this range
1.6. Selection Statements
1.6.1. Relational expressions
The relational operators in MATLAB are:
Operator Meaning
> greater than
< less than
>= greater than or equals
<= less than or equals
== equality
~= inequality
The logical operators are:
Operator Meaning
|| or for scalars
&& and for scalars
~ not
1.6.2. The IF statement
The if statement chooses whether or not another statement, or group of statements, is
executed. The general form of the if statement is:
if condition
action
end
A condition is a relational expression that is conceptually, or logically, either true or false.
The action is a statement, or a group of statements, that will be executed if the condition is
true. When the if statement is executed, first the condition is evaluated. If the value of the
condition is conceptually true, the action will be executed, and if not, the action will not be
executed. The action can be any number of statements until the reserved word end; the
action is naturally bracketed by the reserved words if and end. (Note: This is different from
the end that is used as an index into a vector or matrix.)
1.6.3. The IF-ELSE statement and the SWITCH statement
The if statement chooses whether an action is executed or not. Choosing between two
actions, or choosing from several actions, is accomplished using if-else, nested if, and
switch statements.
The if-else statement is used to choose between two statements, or sets of statements. The
general form is:
if condition
action1
else
action2
end
First, the condition is evaluated. If it is conceptually true, then the set of statements
designated as action1 is executed, and that is it for the if-else statement. If instead the
condition is conceptually false, the second set of statements designated as action2 is
executed, and that’s it. The first set of statements is called the action of the if clause; it is
what will be executed if the expression is true. The second set of statements is called the
action of the else clause; it is what will be executed if the expression is false. One of these
actions, and only one, will be executed—which one depends on the value of the condition.
A switch statement can often be used in place of a nested if-else or an if statement with
many elseif clauses. Switch statements are used when an expression is tested to see whether
it is equal to one of several possible values.
The general form of the switch statement is:
switch switch_expression
case caseexp1
action1
case caseexp2
action2
case caseexp3
action3
% etc: there can be many of these
otherwise
actionn
end
The switch statement starts with the reserved word switch, and ends with the reserved word
end. The switch_expression is compared, in sequence, to the case expressions (caseexp1,
caseexp2, etc.). If the value of the switch_expression matches caseexp1, for example, then
action1 is executed and the switch statement ends. If the value matches caseexp3, then
action3 is executed, and in general if the value matches caseexpi, where i can be any integer
from 1 to n, then actioni is executed. If the value of the switch_expression does not match
any of the case expressions, the action after the word otherwise is executed.
Exercises 7: Whether a storm is a tropical depression, tropical storm, or hurricane is
determined by the average sustained wind speed. In miles per hour, a storm is a tropical
depression if the winds are less than 38 mph. It is a tropical storm if the winds are between
39 and 73 mph, and it is a hurricane if the wind speeds are > = 74 mph. Write a script that
will prompt the user for the wind speed of the storm, and will print which type of storm it
is.
1.7. The FOR Loop
The for statement, or the for loop, is used when it is necessary to repeat statement(s) in a
script or function, and when it is known ahead of time how many times the statements will
be repeated. The statements that are repeated are called the action of the loop. For example,
it may be known that the action of the loop will be repeated five times. The terminology
used is that we iterate through the action of the loop five times.
The variable that is used to iterate through values is called a loop variable, or an iterator
variable. For example, the variable might iterate through the integers 1 through 5 (e.g., 1,
2, 3, 4, and then 5). Although variable names in general should be mnemonic, it is common
for an iterator variable to be given the name i (and if more than one iterator variable is
needed, i, j, k, l, etc.) This is historical, and is because of the way integer variables were
named in Fortran. However, in MATLAB both i and j are built-in values for -1 , so using
either as a loop variable will override that value. If that is not an issue, then it is acceptable
to use i as a loop variable.
The general form of the for loop is:
for loopvar = range
action
end
where loopvar is the loop variable, range is the range of values through which the loop
variable is to iterate, and the action of the loop consists of all statements up to the end. The
range can be specified using any vector, but normally the easiest way to specify the range
of values is to use the colon operator.
Exercises 8: Create a 3 × 5 matrix. Perform each of the following two ways: using built-in
functions, and also using loops (with if statements if necessary):
Find the maximum value in each column.
Find the maximum value in each row.
Find the maximum value in the entire matrix.