Lab 1 Introduction To MATLAB
Lab 1 Introduction To MATLAB
Lab 1 Introduction To MATLAB
Getting started:
1. MATLAB is available from both Windows and Linux. Reboot the PC and select your pre-
ferred operating system.
3(a). To start MATLAB from Windows select the MATLAB icon (double click) from the desktop.
3(b). To start MATLAB from Linux, type matlab & from the command prompt. It is recom-
mended that you first create a subdirectory to hold your MATLAB related file. For example, the
following Linux commands will create a subdirectory called MATLAB in your home directory
(the home directory is the directory which you are automatically placed in upon logging in:
In the above commands, the “ted@deadflowers ~ 2:34pm >” is known as the command
prompt. Your prompt may appear different depending on how your account has been configured.
Linux commands are entered on the command line following the prompt followed by pressing the
enter key. The command to start MATLAB is simply: matlab & . By including the & symbol
on the command line after the word matlab, control will return to the prompt and you will be
able to continue entering commands from that window. If you do not specify the & symbol, con-
trol will not return to prompt until you quit MATLAB.
After a few seconds, the main MATLAB window as shown in Figure 1 will appear:
2
Command window: This is the central window which contains the >> prompt . MATLAB com-
mands are entered from this prompt in this command window and results will be displayed (ech-
oed) in the window.
Workspace window: This are shows any variable which may exist and their values. It should be
initially empty.
Command History: This window is displayed below the Workspace window and it displays a
history of previous commands which may have been entered (during a previous MATLAB ses-
sion).
Current Folder: Located on the top left portion of the main window, it displays any files and
directories which may exist in the working directory from where you started MATLAB from.
3
Assignment operator:
The assignment operator in MATLAB is the = symbol. It is used to assign a value to a variable. A
value can either be a literal, or a MATLAB expression which evaluates to some value.
Let us create a variable called A and assign it an initial value of 5. From the >> prompt in the
command window type the following (followed by the Enter key)
>> A = 5
A =
>>
Observe that the Workspace now contains a variable called A with value 5 size 1x1 and that this-
variable consists of 8 bytes of memory storage. Refer to Figure 2 for details.
>> A = 6.9
A =
6.9000
If you do not wish to have MATLAB echo the results of the command you type in, simply termi-
nate the command with a ; (followed by the Enter key). MATLAB will perform the command but
the results will not be displayed:
>> B = 10 ;
>>
You may have wondered what the 1x1 entry for the Size of variable A in the Workspace window
refers to. MATLAB essentially treats all variables as arrays, a simple scalar variable such as our
A and B in the examples thus shown are treated as a 1x1 array of doubles. MATLAB supports the
following arithmetic operators when working with scalar values: +, -, *, /, ^ . The *
operator is used to denote multiplication, / is the division operator, and ^ is the power operator
used to perform x y. Some examples:
>> lenght = 5
lenght =
>> width = 4
width =
area =
20
>> powers_of_two = 2 ^ 0
powers_of_two =
5
>> powers_of_two = 2 ^ 1
powers_of_two =
>> powers_of_two = 2 ^ 2
powers_of_two =
>> powers_of_two = 2 ^ 3
powers_of_two =
>> powers_of_two = 2 ^ 4
powers_of_two =
16
>> divide_by_zero = 1 / 0
divide_by_zero =
Inf
Interestingly enough, MATLAB returns the answer “Inf” as a result of dividing by 0. Some of
may have come across this symbol from your programming courses. Inf is one of the reserved
values in the IEEE 754 floating point standard and is used to represent infinity. In general, divid-
ing by 0 is usually not a good thing to do...
>> 43
ans =
43
MATLAB will create a variable called ‘ans’ if you do not explicitly assign one yourself.
Operator Precedence:
>> 3 + 4 / 3
Depending on the order in which we perform the two arithmetic operators contained in the
expression the result can be either 2.3333 or 4.333. Which one is correct ???
ans =
4.3333
In MATLAB (just as in any other high-level programming language), the * and / operators are
said to be of higher precedence than the + and - operators. There is a very common mnemonic (
memory aid” which goes along the lines of:
which helps one to remember that Multiplication and Division are to be performed first before
Addition and Subtraction.
3 + 4 ^ 2 / 8 ?
The ^ operator has higher precedence than either multiplication or division and is thus performed
first giving the answer of:
ans =
MATLAB allows the use of parenthesis to explicit force precedence (and to aid in readability of
complex arithmetic expressions) :
>> 3 + ( (4 ^ 2) / 8 )
ans =
7
1-D arrays:
MATLAB also allows one to create one dimensional arrays ( ie. a vector):
>> my_row_vector = [ 1 , 2 , 3 ]
my_row_vector =
1 2 3
When defining a vector, the , used to separate each element may be omitted and a blank can be
used to separate each element:
>> my_row_vector = [ 1 2 3]
my_row_vector =
1 2 3
Note that the size of variable my_row_vector is reported as 1 x 3 array in the Workspace. A
column vector may be created as:
>> my_column_vector = [ 1 ; 2 ; 3 ]
my_column_vector =
1
2
3
Note that the semicolon (;) is used to separate each of the three elements which comprise the
3 x 1 array.
A useful operator when working with arrays is the transpose operator (‘). We may obtain
a column vector from a given row vector by taking the transpose of the row vector (or vice versa).
>> row = [ 4 5 6 ]
row =
4 5 6
col =
4
5
6
Colon Operator:
MATLAB can create an array consisting of a range of numbers by using the colon operator:
>> colon_array_example = [ 1 : 10 ]
colon_array_example =
1 2 3 4 5 6 7 8 9 10
The expression [ 1 : 10 ] will result in a 10 element array consisting of the values from 1 to
10 inclusive. There is an alternative in which one may specify the step size between elements:
>> step_size_example = [ 1 : 2 : 10 ]
step_size_example =
1 3 5 7 9
The first element is set to 1, the second element is set to 1 + step size = 3, the third element is set
to 3 + step size = 5, etc. The general form of the expression is:
To access a particular element of an array, the index of the element is used within (). For exam-
ple:
my_row =
-56 234 12
element =
9
-56
NOTE: In MATLAB array indices start from 1 (and not 0 as in the C and C++ programming
languages). Using an index value of 0 will result in an error:
When working with vectors, MATLAB allows for element-by-element operations. For the + and
- operators this is quite intuitive:
>> A = [ 1 2 3 ]
A =
1 2 3
>> B = [ 4 5 6 ]
B =
4 5 6
>> C = A + B
C =
5 7 9
In this example, we are adding two 1 x 3 row vectors and assigning the result to a third row_vector
called C and the elements of C will be:
>> A = [ 5 6 7 ]
A =
10
5 6 7
>> B = [ 1 2 3]
B =
1 2 3
>> C = A - B
C =
4 1 6
When performing the element-by-element multiplication and division and power, we use the
. operator followed by the specified arithmetic operator. For example:
.*
./
.^
>> A = [ 2 3 4 ]
A =
2 3 4
>> B = [ 5 6 7 ]
B =
5 6 7
>> C = A.*B
C =
10 18 28
The .^ operator is similarly defined, using the same values for A and B, the result of:
>> A = [ 2 3 4 ]
A =
2 3 4
>> B = [ 5 6 7 ]
B =
5 6 7
>> C = A .^ B
C =
32 729 16384
>> A = [ 8 32 64 ]
A =
8 32 64
>> B = [ 4 2 4 ]
B =
4 2 4
>> C = A ./ B
C =
2 16 16
MATLAB allows to multiply a vector by a scalar, or to divide a vector by a scalar, or to raise every
element of a vector by a scalar :
12
>> A = [ 2 , 3, 4 ]
A =
2 3 4
>> A = A * 2
A =
4 6 8
>> A = [ 2 3 4 ]
A =
2 3 4
>> A = A / 2
A =
>> A = [ 2 3 4 ]
>> A = A .^ 2
A =
4 16 64
Matrices:
>> my_array = [ 1 2 3 ; 4 5 6 ]
my_array =
1 2 3
4 5 6
13
my_array is said to be a 2x3 array. It contains two rows and three columns. To access a particular
element within the array, we use the notation array_name(row_index,
column_index) as in:
element =
Array Multiplication:
A =
1 2 3
4 5 6
>> B = [ 7 8 9
10 11 12 ]
B =
7 8 9
10 11 12
We have already seen how we can perform the element-by-element array multiplication of these
two arrays by using the .* operator:
>> C = A .* B
C =
7 16 27
40 55 72
What would happen if we were to try to multiply these two arrays together using the * operator?
>> C = A * B
Error using *
Inner matrix dimensions must agree.
multiplication as defined by linear algebra. Furthermore, there are certain restrictions which are
placed on the sizes of the two arrays which are to be multiplied. In general, if mick is an
(m x n ) array and if keith is an ( n x k ) array, then the resulting array found by multiplying
mick by keith will be of size ( m x k ) . Stated in other words, the number of columns in the
first array must be equal to the number of rows in the second array:
>> mick = [ 1 2 3 ; 4 5 6 ]
mick =
1 2 3
4 5 6
>> keith = [ 7 8 ; 9 10 ; 11 12 ]
keith =
7 8
9 10
11 12
stones =
58 64
139 154
Complex Numbers:
>> complex1 = 2 + 3i
complex1 =
2.0000 + 3.0000i
>> complex2 = 3 + 5j
complex2 =
3.0000 + 5.0000i
Note that we may use either the symbol “i” or “j” to denote the imaginary part of the complex
number. To add these two complex numbers, we simply perform:
15
complex_sum =
5.0000 + 8.0000i
MATLAB uses the rules of complex arithmetic to perform addition, subtraction, multiplication
and division of complex numbers:
complex_product =
-9.0000 +19.0000i
complex_division =
0.6176 - 0.0294i
complex_vector =
Plotting:
MATLAB provides very powerful graphing capabilities which allows for the creation of either
two-dimensional or three-dimensional plots. Suppose we wish to plot the equation of the straight
lien defined by the equation:
y = 3x
We know this line will have a slope of three and intercept the x-axis at 0. Let us use MATLAB
plot this line. First we define the points on the x-axis using a row-vector:
>> X = [ 0 , 1, 2 ,3 ]
X =
16
0 1 2 3
Next, we compute the y-value for every x value by multiplying every element in the X vector by 3
and assigning the result to another row vector called Y:
>> Y = 3 * X
Y =
0 3 6 9
>> plot(X,Y)
The plot function will plot the elements of the second argument (Y in this example) as a function
of the elements in the first argument (X) . In other words, the elements of Y will be plotted on the
vertical y-axis positioned at a location on the x-axis as specified by the elements of vector X.
Figure 3: Plot of Y = 3X
17
There is a variation of the plot command called stem which does not connect the data points, but
simply indicates them with circles and vertical lines (refer to Figure 4) :
>> stem(X,Y)
Descriptive labels to the x and y axes and a title may be added to plots by using the xlabel,
ylabel, and title commands:
>> xlabel(’X’)
>> ylabel(’Y = 3X’)
>> title(’A plot of the function y = 3x from x = 0 to x = 3’)
M-file Scripts:
MATLAB commands may be saved in a text file, such a file is called a MATLAB script M-file.
The script may be loaded into MATLAB and the commands within the file will then be per-
formed. A script may be created using any text editor such as Windows Notepad, or gedit, vi,
emacs, etc. if you are using Linux. MATLAB has a built-in editor as well which may be accessed
by selecting File -> New -> Script . The editor window will appear as shown in Figure 5.
18
Enter the following script and save it by selecting File -> Save and specify a file name such as
“sample.m” in the Select File for Save As window.
% This is a comment
% Sample M-file script
% Ted Obuchowicz
% April 19, 2012
clear
% define the input vector
X = [ 1 2 3 4];
% 2
% define the output as y = x
Y = X .^2;
19
plot(X,Y)
Note that this example script introduces a new MATLAB command called clear. The clear
command clears the workspace of any variables (which may be present from some earlier MAT-
LAB commands entered).
Once you have saved the file, exit from the editor by selecting File -> Close Editor
A script file may be loaded into MATLAB by typing in the name (the filename extension .m is not
necessary and may be omitted) of the script from the MATLAB command prompt in the Com-
mand window:
>> sample
An alternative method of running a script is to select it with the mouse by navigating to its loca-
tion in the Current folder window and right clicking and selecting Run from the pop-up menu.
MATLAB has a built-in help utility. To learn more about a certain command simply type help fol-
lowed by the command:
Various line types, plot symbols and colors may be obtained with
plot(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:
>> help
HELP topics:
Questions
In order to answer the following set of questions, a some self-study is required. Use the online
help facility available in MATLAB to learn how to use the new commands introduced in each of
the following questions. Create script files for each question. Include your name and ID as com-
ments in the script files. For each question, submit as part of the written lab report the script file
and any required plots.
Question 1:
Familiarize yourself with the subplot and hold command. Using the subplot and plot
commands, plot the volume of a sphere as a function of it’s radius for values of radius from 1 to
10. On the same graph plot the surface area of a sphere as a function of the radius ( from radius =
1 to 10). Use different colors for the two plots ( help plot will give details on how to select
colors).
Make use of the built-in MATLAB function called pi which returns the value of pi.
The plots for the sphere’s volume and surface area are to be plotted in the left-hand pane
of the plot window.
Repeat the above two plots, but this time plot the volume of a square and surface area of a square
as a function of its length from 1 to 10. These plots are to be graphed in right-hand pane of the
plot window.
Label each axes as appropriate and include titles for the plots.
Question 2:
MATLAB has two useful functions when working with arrays: zeros and ones. To create a
10 element row_vector consisting of all zeros, the zeros function can be used as in:
>> Y1 = zeros(1,10)
Y1 =
0 0 0 0 0 0 0 0 0 0
22
We can then use array element notation to set a few of these elements to some other value ( 1 for
example):
>> Y1(3) = 1
Y1 =
0 0 1 0 0 0 0 0 0 0
The ones function can be used to create a row vector consisting off all 1s :
>> Y2 = ones(1,10)
Y2 =
1 1 1 1 1 1 1 1 1 1
>> Y2(6:10) = 0
Y2 =
1 1 1 1 1 0 0 0 0 0
Y2(6) = 0
Y2(7) = 0
Y2(8) = 0
Y2(9) = 0
Y2(10) = 0
Using the zeros and ones functions, create two different row_vectors: the first vector is to
consist of all zeros except for two elements (which two are to be 1 is left up to you). The second
vector is to consist of the first n elements being 0, and the remaining elements all equal to 1. The
value of n is arbitrary. Plot in one window stem plots of these two vectors as a function of x as x
varies from -5 to +4 in the left hand pane, and as x varies from 0 to 9 in the right half pane. Refer
to the following figure for details:
23
Question 3:
>> n = [ 0 : 7 ] ;
>> N = 4 ;
>> x = sin ( (2*pi)/N * n );
>> stem(n ,x ) ;
The value of N defines the number of samples per period, and n defines the total number of data
points stored. In the above example, we are sampling the discrete time sinusoidal signal 4 times
every period and storing these sampled values into a vector consisting of 8 data points. The result-
ing stem plot is:
24
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
With more samples per period, the sampled signal more closely resembles a sine wave.
You can easily see the effect by doing:
>> N = 16 ;
>> n = [ 0 : 31 ] ;
>> x = sin ( (2*pi)/N * n );
>> stem(n,x);
(i) A signal X[n] is said to be periodic (with period T) if X[n + T] = x[n]. This question investi-
gates the effect how floating point numbers are stored internally within a computer. Sample the
signal x = cos( (2*pi)/1024 * n ) over 4 periods and then determine whether x[n] = x[n + 1024].
For example, you can compute the difference of x[1] - x[1+1024] to see if it is equal to 0.0. It
would be useful to use the:
command so that doubles are displayed to their full 15 decimal place accuracy.
(ii) Instead of using the MATLAB constant, pi, use the value of 3.14 and compare your results
with those obtained in part (i) .
x1 = cos(pi/4* n + pi/3)
and
x2 = cos(9*pi/4.*n + pi/3)
25
Question 4:
MATLAB has the capability of reading information stored in ASCII text files and assigning this
information to variables. Create an ASCII text file consisting of the following 100 numbers:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 23 24 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 62 64 65 66 67 68 69 70
71 72 72 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
Use the load command to read in these 100 numbers and store the values into an array called
my_big_array.
References
Recommended texts
2. MATLAB for Engineering Applications, William J. Palm III, McGraw-Hill, ISBN 0-07-
047330-7, 1999.
4. MATLAB 5 for Engineers, Adrian Biran and Moshe Breiner, Addison-Wesley, ISBN 0-201-
36043-8, 1999.
T. Obuchowicz
May 2, 2016