|ECE 241L * Intro to EE Lab
Lab 2 : MATLAB Basics
Objective: To become familiar with the basics of MATLAB including making plots, saving and running m-files, writing a program using arrays.
Equipment: Computer with MATLAB installed
Introduction: MATLAB stands for MATrix LABoratory. It is a matrix processing language that is used for scientific and engineering data processing. It handles both numeric and symbolic variables and can be used either interactively (in the Command Window) or through input (‘m’) files. It is sold by MathWorks, Inc.
If you are familiar with MATLAB: this lab will be a review. Take this opportunity to refresh your memory, fill in any gaps you missed the first time, and improve your knowledge by helping those students who have not had experience with MATLAB before.
For those new to MATLAB: this lab presents some of the basic capabilities of MATLAB, but it is not a program that you learn in one lab. I expect you will continue to practice and learn more about MATLAB throughout other courses. As you work, you can find help in many textbooks, User’s Guides, the MathWorks web site, by accessing the help window, or type help command or just help. If your lab partner is familiar with MATLAB already they can assist you, but make sure you understand and do the exercises yourself.
Before the lab:
Go to the MathWorks web site (www.mathworks.com) Go to Academia, Interactive Tutorials, MATLAB tutorial. There are about two hours of tutorials here. How much time you spend is up to you, depending on your previous experience. Those who have been introduced to MATLAB before will probably not need this at all, but take a look just to see what is there and use it as a reference if needed. For those brand new to MATLAB, I suggest you check out the MATLAB Fundamentals tutorial under MATLAB On-Ramp, then come back to other tutorials later as needed.
In addition, look through the tutorial that follows below. This provides a summary of commands that should be useful as you work through the exercises that follow. Look it over quickly before the lab, then refer to it as needed in the lab – its not going to make a lot of sense until you try it!
Introduction to MATLAB tutorial
Using interactive mode
In the Command Window, type in an equation and hit enter, just like using a calculator. The order of operation is: exponentiation (^) first, then multiplication and division (* /), then addition and subtraction (+ -). You can always use parentheses. For example, typing 2 + 3 * 5 – 4 * 2 + 2^3 gives the same as 2 + (3*5) – (4*2) + 23 = 17 (try it!)
Names must start with a letter, then you can use any letters, numbers, or underscore ( _ ) up to 31 characters long. Variables are case sensitive and cannot contain any punctuation marks. Avoid using reserved names (sin, pi, i, j, etc.) to avoid confusion. The command clear will clear the memory of any previous assignments.
Some special symbols:
% comments – anything on the same line after this is not an operation
… continue on next line
; suppresses printing to the screen (when used at the end of a line), or starts a new line in an array
: creates an array (a:b:c creates an array from a to c in steps of b)
There are many built in functions. Most are obvious, such as sin(x), cos(x), etc. Some other useful ones are: sqrt(x), exp(x) and mean(x). Sometimes they are not so obvious, such as log(x) = natural log, log10(x) = common log (base 10). There are many more! A useful command is lookfor. For example, typing lookfor plot will return all the functions associated with plots. Then you can use help to get the exact syntax.
Variables can be scalars, vectors or matrices without any declaration. Vectors and matrices are entered in square brackets . Some examples:
A = 2 (scalar),
B = [1 2 3] (row vector),
C = [1 2 3]’ or C = [1; 2; 3] (column vector),
D = [1 2 3; 4 5 6; 7 8 9] (3x3 matrix)
Arrays can be created with the colon ( : ) operator or with the linspace or logspace command. For example, x = 0:0.1:1 (from 0 to 1 in 0.1 steps) or linspace(0,1,11) (from 0 to 1 with 11 elements) both create x = [0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1].
MATLAB’s strongest feature is its ability to manipulate vectors and matrices. Here are some useful matrix operations:
* multiplication – scalar, vector or matrix, depending on the variable type
length(A) length of vector A
size(A) gives (m,n) for an m x n matrix
. element-by-element operation For example, .* causes each element of a matrix to be multiplied by the corresponding element of another matrix, rather than performing matrix multiplication.
A typical problem is to solve for a vector X in the equation AX = B. This can be done one of two ways: X = inv(A)*B or X = A\B. In most cases, either operation is fine. In the case of an ill-conditioned matrix, the second method will be more efficient and accurate.
Some special matrices that may come in handy are zeros(n), ones(n), , rand(n) and eye(n).
To address a matrix element aij, the notation is A(i,j). The colon symbol ( : ) indicates all of a row or column. Saying a:b indicates rows or columns from a to b. For example, A(:,1:2) addresses all rows, columns 1 – 2, as shown:
» A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
M-Files (scripts & functions)
Usually you will want to save programs in a file to debug and to use again. Choose New from File menu to open the Editor Window. Type all commands in the editor and save the file as filename.m. Run the file from the Debug menu, or use the Run button on the toolbar, or type filename in the Command Window.
Ordinary script files are simply a self-contained list of commands, while functions are used to pass variables in and out. The first line of the function file must have the format:
function output = filename(inputs) or function [outputs] = filename(inputs)
Run the file by typing filename(input values)
The MathWorks tutorials “Automating Analysis with Scripts” and “Writing Functions” have more information.
Polynomials are represented by a vector of coefficients. For example, the polynomial
x2 + 2x + 3 would be represented by p = [1 2 3]. Some useful polynomial commands:
polyval(p,x) - evaluate the polynomial at the given value of x
roots(p) - find the roots of the polynomial
p = poly(r) - construct the polynomial from roots r = [r1, r2, …]
conv, deconv - multiply or divide polynomials
Input and Output
Besides using functions, another option to get data into a program is to prompt the user for input. The line:
x = input(‘enter number’)
will cause the instruction “enter number” to appear on the screen, then assign the number entered by the user to the variable x.
There are many options for displaying outputs. The result of any command without ; at the end will show on the screen. Some other examples are given here.
disp(x) - display output without variable name
num2str(x) - convert output to string. Example:
result = [‘The number is ‘ num2str(x)]
fprintf - display formatted output.
\n - start a new line
%x.yz - formats a number with x = field width, y = precision and z = notation
(e for exponential, f for floating point, i for integer)
Example: fprintf(‘The answer is %x.yz’,variable)
This command has many options, type help fprintf to see more.
The command plot(x,y) (where x and y are arrays) creates a 2-dimensional plot of y versus x. The arrays need to be the same size.
The commands to add a plot title, axes labels and legend are title, xlabel, ylabel and legend. They all use the format command(‘…’), for example, title(‘My Plot’). These, as well as other additions like text boxes and arrows, can also be added in the graphics window after the plot is drawn.
There are many other plotting features, more than will be listed in this tutorial. A few useful ones are given here. Type help plot for more information.
plot multiple lines on one graph: plot(x1, y1, x2, y2, …)
use different line styles, colors and data point symbols: plot(x,y,‘…’)
turn grid on or off: grid on or grid off
keep the plot window open to add another plot: hold on (hold off)
change axes range: axis([xmin xmax ymin ymax])
make multiple plots on one page: subplot(a,b,c), plot(x,y) makes a rows and b columns of subplots, and puts this plot in position c
3-d plots include surf, mesh and contour
Try this example:
x = [1 2 3]
y1 = [4 6 10]
y2 = [5 7 11]
plot(x, y1, ‘r’, x, y2, ‘k--’)
The MathWorks tutorial “Visualizing Data” has more information.
LOOPS – For, While, If
The format of a for loop is given below. This loop will run through the given values of t (from start to stop using the given step size) then end.
for t = start:stepsize:stop
The format of a while loop is given below. This loop will run as long as the given logical condition is true, and will end when the logical condition becomes false.
while logical condition
The format of logical operators is:
<= less than or equal to (e.g., while x <= y)
>= greater than or equal to
~= not equal to
== equal to
The format of an if loop is given below. The commands in the if loop will only be executed if the condition is true, otherwise they will be ignored.
if logical conditions
Some variations: if logical conditions
This process can be continued with elseif. The command break jumps to the next statement after the loop.
I. This first section consists of exercises to try on your own for practice, as much as you need depending on your experience. Take your time and make sure you understand everything in this section before going on. These exercises are not to be turned in, but there are problems in section II that are to be turned in.
1. Try a few commands in interactive mode. Example: x = 1:10
y = x.^2
What happens if you don’t use the dot command? What happens if you end the line with ; ?
2. Enter matrices, multiply, find the inverse and determinant.
Example: A = [1 2 3; 4 5 6; 7 8 9]
B = [1 3 5; 2 4 6; 0 0 1]
What does A.*B do?
3. Write for, while and if loops. Examples:
for k = 1:10
y = 2^k
b) k = 0
y = 2^k
k = k+1
c) k = 1
if k < 10
y = 2^k
Be careful of “endless” while loops! For example, what would happen in b) if you did not increment k to k+1?
4. Practice polynomial functions. Example: p = [1 2 3 4]
x = 1:10
5. Make a plot. Example: x = 1:.01:10;
y1 = exp(x);
y2 = exp(2*x);
Draw the two lines in different line styles and colors (see help plot.) Add axes labels, a title and a legend to your plot.
6. Write, save and run an m-file. Use one of the above examples, or make up your own.
7. Explore the help window and the help command.
II. When you’re comfortable with the basics, work on the following problems. Save your input commands in m-files to turn in. The m-files must include comments explaining each step. Turn in both the m-files and the outputs (plots for problems 1 and 3, print the screen showing the output for problem 2.) It is most convenient if you save all the input and output information in a single .pdf or .doc file to submit.
1. Write a Matlab m-file to plot two sine waves, one with an amplitude of 1 and a frequency of 1 MHz (106 Hz) and the other with an amplitude of 0.8 and a frequency of 2 MHz. Your graph should show at least 2 periods of each wave, and should include axis labels, title and legend.
A sine wave is given by sin(2ft), where f is the frequency in Hz. Remember the period of the wave is 1/f. You will need to figure out the appropriate time scale for the frequencies given.
2. Write a program to compute a student’s grade as follows:
i) Prompt the user to enter a list of homework grades, and compute the average. The list is of unknown length. One suggestion: instruct the user to enter the grades in square brackets, e.g. [1 2 3 …], and use the mean function to find the average. Another idea: have the user input a negative number at the end of the list, and use a loop that will end when the number is < 0.
ii) Repeat for a list of quiz grades.
iii) Have the user enter a single final grade.
iv) Finally, compute and output the total grade. The quizzes should be weighted to be 50% of the grade, the final 30% and the homework 20%.
Try it with the following numbers, and turn in the result of this example:
HW grades: 95, 79, 87, 76, 82, 99, 91
Quizzes: 80, 88, 92, 94, 78
[You should get an answer of 87.3]
3. Extra Credit This one is a bit more challenging. You don’t have to do it, but give it a try if you can!
Background. This problem involves a Fourier series. The math behind this problem is something you may not have learnt, but we are just using it as an example to calculate and plot some rather complicated equations in MATLAB.
The idea behind the Fourier series is that any periodic signal can be represented by an infinite sum of harmonically-related sinusoidal signals, either using sines and cosines, or using complex exponentials:
(“j” is the imaginary number.) The term 0 is the fundamental frequency of the periodic signal, 0 = 2/T, where T is the period. Frequencies n0 , where n is an integer, are the harmonics. This infinite sum is an exact representation of the original function. If we use a finite sum, where n goes from –N to N, we will get an approximation “xF(t)”.
In this problem we will calculate and plot the Fourier series representation of a square wave with period T, and compare it to the original function. In other classes you may learn how to derive the coefficients an. For now we will just give you the equation:
Procedure. Write a MATLAB program that will:
a) Calculate the Fourier series coefficients an from equation (2) for a given N;
b) Construct the Fourier series xF(t) from equation (1), and plot it for two periods;
c) Plot two periods of the actual square wave x(t) on the same graph.
Note that the first step gives you an array of 2N+1 coefficients. The second step gives an array in t (use a small enough resolution to get a smooth plot) where each point in t is found by summing over n. This program can be done using array operations, or loops, or a combination of both. There is not a single right way, but I think you will find array operations much more concise – and one of the great advantages of using MATLAB. One suggestion that I know works well: (i) define t, (ii) calculate x(t) for a single n, (iii) go through a loop to sum over n.
The square wave should have amplitude ±1 and T = 1 s. Run your program with N = 10, 100 and 1000. Turn in the well-commented m-file and the three plots, along with a brief discussion of the results, for your lab report.
ECE 241L Lab 2 2012 MH