Lab #1 Supplement: Introduction to MATLAB
Purpose
In this lab, you will be introduced to MATLAB. For this class, it is important that you are able to use MATLAB to evaluate expressions containing complex numbers. It is also important that you are able to import and export data to and from MATLAB, and are able to play sound files. MATLAB's plotting capabilities will be introduced (they will be used extensively in all labs). You will also use M-files and create some simple signal processing functions.
Objectives
It is advised that you review the complex numbers page before proceeding with this lab.
By the end of this laboratory assignment, you should be able to:
Introduction
- Load and play a sound file (ASCII text format).
- Use MATLAB to perform complex arithmetic.
- Generate and plot signals and complex valued functions.
- Write new functions in MATLAB using M-files.
- Load and save results of computations from a MATLAB session.
MATLAB behaves as a high-level programming language that is tailored for signal processing, communication, and control tasks. It is used by professionals in industry and academia worldwide in research, development, and design. MATLAB is short for MATrix LABoratory, and works on matrices of numbers. We will focus mostly on one-dimensional matrices (i.e. vectors) that contain signal samples, or on multiple-dimensional matrices containing several signals or the parameters of a system. We will first focus on familiarizing you with the matrix notations in MATLAB, and get you used to working with vectors and matrices in arithmetic operations. It may be helpful to follow this supplement with MATLAB running.
Using MATLAB
MATLAB is available on PCs and Macs in computing labs on campus. You can find a list of available computer labs on the Academic Computing Services website (http://insci14.ucsd.edu/acs_sql/scripts/show_facilities.php?action=0)
Starting MATLAB
Mac or PC: Find the MATLAB icon and double click. If it does not start properly, try closing other applications first (MATLAB may require more memory).
The Help Command
Arguably the most useful command in MATLAB is the help command. To get help on a command, type 'help [command]' in the command window.
Creating new variables
>> help for
{displays help on for loops}
>> help while{displays help on while loops}
You can also click on the Matlab help button or pull down menu, or type "Matlab [command]" in your favorite search engine.
If you are unsure if a certain command exists, take a few guesses using help or a search engine. Chances are MATLAB will have it.
MATLAB is written to operate on matrices. You will often encounter matrices that represent signals in these labs. For example, a monaural audio signal can be represented in MATLAB as a 1 by N matrix (or an N by 1 matrix), where the element values are samples of the signal in time. Every matrix in MATLAB is indexed starting at 1. For example, if X is a 5 x 5 matrix, element X(1, 1) is the first; element X(0,0) is not definable in MATLAB.
Evaluating Complex Variables and Expressions
There are many different ways to create new variables:
>> M = 10;
{creates variable M, sets it to 10}
>> A = zeros(M, N);{creates a matrix of zeros A with M rows and N columns}
>> A = ones(M, N);{creates the same matrix A, but initialized to all ones instead of zeros}
>> b = 0:100;{creates matrix A with one row and 101 columns, which contains the series 0, 1, 2, ... , 99, 100}
>> k = [1 -1 3 7 5];{creates the matrix k, with 1 row and 5 columns, with values}
>> k = [1; -1; 3; 7; 5];{creates the matrix k, with 5 rows and 1 column, with values}
>> x = z(:, 5);{creates the matrix x, which is the 5th column of z}
>> x = z(3, :);{creates the matrix x, which is the third row of z}
Be careful to distinguish between mathematical functions that operate on the matrix as a whole vs. the elements of the matrix. For example, one must choose between the cross product and the dot product when multiplying two matrices. MATLAB calls functions that operate on the elements of a matrix 'array operators,' and calls functions that operate on the matrices themselves 'matrix operators.' The dot product is an example of an array operator, whereas the cross product is an example of a matrix operator. Here are some common mathematical operators in MATLAB:
Plotting functions
Char Name HELP topic + Plus arith - Minus arith * Matrix multiplication arith .* Array multiplication arith ^ Matrix power arith .^ Array power arith \ Backslash or left division slash / Slash or right division slash ./ Array division slash ' Transpose punct = Assignment punct == Equality relop < > Relational operators relop & Logical AND relop | Logical OR relop ~ Logical NOT relop xor Logical EXCLUSIVE OR xor
Here are some useful functions:
abs(x) returns the magnitude of x. angle(x) returns the phase angle of x. real(x) returns the real part of x. imag(x) returns the imaginary part of x. conj(x) returns the complex conjugate of x. rem(x, y) returns the remainder of x divided by y. cos(x) returns the cosine of x where x is in radians. sin(x) returns the sine of x where x is in radians. size(x) returns the dimensions of the matrix x. length(x) returns the greatest dimension of x. max(x) returns the largest element in x. min(x) returns the smallest element in x. ceil(x) returns the smallest integer greater than or equal to x. floor(x) returns the largest integer less than or equal to x. zeros(a, b, c...) returns an (a x b x c x ...) matrix of zeros. ones(a, b, c...) returns an (a x b x c x ...) matrix of ones. who returns a list of currently defined variables.
MATLAB uses 1i to represent the square root of -1 (It will also recognize i and j, but these forms are not recommended as you may use these variables in your script for other purposes.). Thus the complex number (5 + 2i) can be defined as follows:
>> a = 5 + 2*1i;
The semicolon is not required at the end of a command in MATLAB. If it is omitted, MATLAB will echo back the return value. Often this is undesirable, resulting in pages of scrolling data.{a = 5 + 2i}
To plot a function, use plot or stem. Plot(x) will plot all the points in x, connecting one point to the next. Stem(x) will draw each point, circle the point, and draw a line from that point down to the x axis. Plot is better for plotting functions that have a lot of points, while stem is better for plotting smaller functions, or when it is important to view the data as discrete values.
>> plot(real(x));
{plots the real values of the function x}
>> stem (angle(x));{plots the phase of x, viewed as discrete values}
Useful functions:
subplot(n, m, x);
{divides the graph window into n rows and m columns, and makes the square x the active sub-graph. Graphs are numbered from left to right, and then from top to bottom.}
title('Text to appear in title');{Prints 'Text to appear in title' above the current subplot graph}
xlabel('label for x axis');{Prints 'label for x axis' under the x axis in the current subplot graph}
ylabel('label for y axis');{Prints 'label for y axis' under the y axis in the current subplot graph}
axis([x1 x2 y1 y2]);{Zooms in the current graph so that the dimensional boundaries are from x1 to x2 on the x axis, and from y1 to y2 on the y axis. Axis(auto) returns the normal axis.}
figure(n);{opens a new graph window, labeled 'figure n'}
Printing
Please refer to the web page https://acms.ucsd.edu/students/print/.
Loading and Saving Files
Binary Files
Playing sound files
MATLAB has several ways to load and save variables. The method you will probably use the most works using the 'load' and 'save' commands. 'Save [filename]' saves all variables into one binary MATLAB file called [filename]. It is not necessary to provide a file extension (MATLAB automatically appends [filename] with '.mat'). To save only certain variables, type the variable names after [filename]. For example
>> save results x;
{saves variable x in binary file 'results.mat'}
>> save bob x y z;{saves variables x, y, and z in binary file 'bob.mat'}
To load binary .mat files, type 'load'.
>> load bob;
{loads 'bob.mat'}
To see what variables are currently defined (such as the ones that you have loaded), use the 'who' command.
ASCII Files
You can save a variable in ASCII text format using the same 'save' and 'load' commands. Just type '-ascii' after your variable.
>> save somefile x -ascii;
{saves x in ASCII text format, in file 'somefile'}
>> load somefile -ascii;{loads the variable stored in the ASCII file somefile, and calls the variable 'somefile' (see below)}
MATLAB does not put a file extension on the end ofwhen saving in ASCII text format, thus it is necessary to use the '-ascii' switch when loading an ASCII text file. It is recommended that you do not use the ASCII feature of the 'save' command for several reasons. For one, MATLAB claims to be able to save and load multiple variables in one ASCII text file, but it cannot load more than one variable in an ASCII text file using the 'load' command, nor can the 'load' command read an ASCII text file generated by the 'save' command when the file contains more than one variable (see 'help save' and 'help load'). Another reason is that you do not have much control over the text formatting using this approach. The ASCII feature of the 'load' command should be used with caution; it can only load data from an ASCII file if that file contains data arranged in a rectangular matrix for only one variable.
Saving and loading ASCII text data can be accomplished more reliably using 'fopen', 'fprintf', 'fscanf' and 'fclose'. These commands are similar to the C commands of the same names. These commands also provide a mechanism to format the data in your text file.
Save example:
>> FID = fopen('somefile.ascii', 'w');
{gets file id for somefile.txt, write permission}
>> fprintf(fid, '%f\n', x);{writes the contents of matrix x as a list of floating point numbers}
>> fclose(FID);{closes file; returns 0 if successful, -1 if not}
Load example:
>> A = zeros (10, 5);
{creates a matrix with 10 rows and 5 cols}
>> FID = fopen('somefile.ascii', 'r'){gets file id for somefile.txt, read permission}
>> A = fscanf(fid, '%f', size(A));{fills matrix A with data}
>> fclose(FID);{closes file; returns 0 if successful, -1 if not}
For more information on these commands, type 'help'.
MATLAB represents a sound file just like it represents any other signal: as a matrix. The command 'SOUND(X, Fs)' plays the matrix X at the sampling rate Fs. On a Mac, it is important to specify the sampling rate to be 8 kHz since the default sampling rate could vary (not sure if this is still true - KBQ). When using the sound command it is good practice to explicitly list the sampling rate.
Loops and Conditional Statements
>> sound(x, 8000);
{plays matrix x at 8 kHz}
Loops are not very desirable, since they take a long time to run on MATLAB relative to using vector operations to accomplish the same result. You will be able to rewrite a loop into expressions containing only vector operations some of the time, and it is recommended that you do this when possible. For the short scripts that you write in this course there will likely be little speedup, but it is good practice for when you run more computationally intensive code. Do not go to extremes, however. If it takes a great deal of time to optimize a short code that you will not be reusing, go ahead and use loops.
Writing functions using MATLAB M-files
If-Then syntax:
IF variable, statements; END
>> if x > y, a(x) = 10; a(x+1) = 20; end;
If-Then-Else syntax:
IF variable, statements; ELSEIF variable, statements; ELSEIF ... ELSE statements; END
>> if x == y, a(x,y) = 2; elseif abs(x-y) == 1, a(x,y) = -1; else a(x,y) = 0; end;
For Loop syntax:
FOR variable = expr, statement; ...; statement; END
>> for x = 1:N, for y = 1:N, a(x,y) = 1/(x+y-1); end; end;
While Loop syntax:
WHILE variable, statement; ...; statement; END
>> while N > a(N), x = x + y; y = a*y/N; N = N - 1; end;
Finding ways to rewrite loop statements in terms of matrix operations can save run time as well as make for more compact coding. Here is a small routine that demonstrates how matrices can be used instead of loops:
>> y = 10:20;
{defines a (1 x 11) matrix, initialized to 10 .. 20}
>> y = 2*y;{every element of y has been multiplied by 2}
>> n = 1:5;{defines a (1 x 5) matrix, initialized to [1, 2, 3, 4,5]}
>> x(3*n) = y(n);{creates a new variable x, and every (3*n)'th element of x (i.e., every third element of x) is set equal to the n'th element of y.}
>> k = y(2*n);{k gets every other element of y}
A MATLAB M-file is a text file that contains instructions for MATLAB to execute. MATLAB executes each line in an M-file as if you were typing in each line at the command prompt. There are two kinds of M-files: functions and procedures. A function is a special kind of procedure that operates locally rather than globally. This means that a function is incapable of modifying existing variables (other than the variable that it stores the return value in) and is incapable of creating new (permanent) variables. A procedure can (and will) do both of these things if instructed to, so one should be careful when modifying values in a procedure.
You can write your own functions in MATLAB using functions that already exist in MATLAB by storing the function in an M-file. An M-file is just a text file, and can be created using any text editor (such as EMACS, PICO, or VI in UNIX, or simple text on the Macintosh). The elements in this file that are required in order for MATLAB to recognize it as a valid function are:
The filename and the function name should be the same.(i.e. function 'blackbox' is contained in a file called 'blackbox.m')
The M-file must start with the word function to indicate to MATLAB that it is a function that may require inputs.
The matrix [output] is the function output.
Consider the following example of a function called 'blackbox.' Blackbox takes two input parameters, a and b, adds one to a, multiplies b by 2, and then multiplies the two modified numbers together, returning one value (i.e., blackbox(a, b) = (a+1) (2b)):
function [output] = blackbox(a, b)
Lines 2 through 7 are printed when help is requested for your function (help blackbox prints these lines). The blank line (line 8) tells MATLAB where the end of the help description is. Parameters a and b are supplied by the function call, and are defined only inside the function. This means that you must supply the input to the function in order to produce an output:
% Adds 1 to argument a and multiplies b by 2
% Returns the product of a and b in the output.
%
% If the two variables are not of the same size,
% the larger variable is stripped to be the same
% size as the smaller.
% Determine the lengths of each vector
la = length (a);
lb = length (b);
% Add 1 to a
a = a + 1;
% Multiply b by 2
b = b*2;
% Compare the lengths: if a is shorter than b, truncate b
% Otherwise, truncate a.
if la < lb,output = a .* b(1:la);
elseoutput = a(1:lb) .* b;
end;
% End of blackbox
>> result = blackbox(3, 4);
{32 is stored in result}
>> a = 5;
>> b = 2;
>> c = 3;
>> d = 6;
>> result = blackbox(c, d);{48 is stored in result, a still equals 5, b still equals 2; MATLAB does all operations on c and d 'inside' blackbox}
If MATLAB does not recognize your new functions, check that your function conforms to the three rules listed above. To get around path problems, it may be necessary to drag your M-file into the MATLAB folder (Macintosh only). In UNIX, try starting MATLAB in the same directory that the M-file is stored in (or moving the file to the directory that MATLAB was started in).
Lab #1 Assignment
This page maintained by psiegel@ucsd.edu.