Sie sind auf Seite 1von 10

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.

It is advised that you review the complex numbers page before proceeding with this lab.

Objectives

By the end of this laboratory assignment, you should be able to:

1. Load and play a sound file (ASCII text format).


2. Use MATLAB to perform complex arithmetic.
3. Generate and plot signals and complex valued functions.
4. Write new functions in MATLAB using M-files.
5. Load and save results of computations from a MATLAB session.

Introduction

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 a number of platforms (SUN/UNIX, PC/Windows, Mac) 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

1. SUN machines: Type matlab at a shell prompt.


2. Macintosh: Find the MATLAB icon in the 'Math Programs' folder. Double click its icon. If it does
not start properly, try closing other applications first (MATLAB may require more memory).

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


The Help Command

Arguably the most useful command in MATLAB is the help command. To get help on a command,
type 'help [command]'.

>> help for


{displays help on for loops}

>> help while


{displays help on while loops}

If you are unsure if a certain command exists, take a few guesses using help. Chances are MATLAB
will have it.

Creating new variables

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.

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}

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


Evaluating Complex Variables and Expressions

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:

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.

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


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 i to represent the square root of -1. Thus the complex number (5 + j2) can be
defined as follows:

>> a = 5 + 2*i;
{a = 5 + j2}

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.

Plotting functions

To plot a function, use plot or stem. Plot(x) will simply 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'}

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


Printing from a Macintosh

It is strongly recommended that you invest in a laser account if you do not already have one. To get
a laser account, go to account services on the first floor of AP&M. To print from a Macintosh, you
must first be connected to your laser account. Directions for connecting to your laser account are
posted in the Mac labs. Once you are connected, you can print by typing 'print' in MATLAB.

Macintosh example:

>> orient landscape;


{orients the printer to take advantage of the paper size.}

>> print;
{prints the current graph (all sub-graphs included)}

Printing from a UNIX machine

Printing out a graph is accomplished in two steps. First, the graph is printed as a post-script file, and
then the post-script file is sent to the printer in UNIX, the same way you print out any post script
file.

SUN example:

>> orient landscape;


{orients the post script file to take advantage of paper size.}

>> print -deps filename.eps


{prints the current graph (all sub-graphs included) to the post-script file 'filename.eps'}

>From UNIX, type the following:

% lpr -Pprinter filename.eps

Loading and Saving Files

Binary 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'}

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


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 of when 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}

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


>> 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 '.

Playing sound files

One important difference between the available Power Mac's and SUN machines is the sound
hardware. The SUN machines available to you have a fixed sampling rate of 8 kHz when playing
back sound files, whereas the Power Macs in EBU2 338 can play sounds at various sampling rates
(including 8 kHz, 22.05 kHz, and 44.1 kHz). Because of this limitation, all sound files in this class
will have a sampling rate of 8 kHz.

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 Macintosh, it is important to
specify the sampling rate to be 8 kHz since the default sampling rate could vary. On a SUN, it is not
necessary to specify a sampling rate; no matter what number you enter as Fs, the matrix will be
played at a sampling rate of 8 kHz.

>> sound(x, 8000);


{plays matrix x at 8 kHz}

Loops and Conditional Statements

Loops are not very desirable, since they take a very long time to run on MATLAB. 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 whenever it is possible. There will be times when loops cannot be
easily translated into vector operations, so it may be worthwhile to learn how to use them in
MATLAB.

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

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


>> 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 saves a lot of time. 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}

Writing functions using MATLAB M-files

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 matrix [output] is the function output.

The M-file must start with the word function to indicate to MATLAB that it is a function that may
require inputs.

Consider the following example of a function called 'blackbox.' Blackbox takes two input

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


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)


% 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);
else
output = a(1:lb) .* b;
end;

% End of blackbox

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:

>> 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).

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]


Lab #1 Assignment

This page maintained by psiegel@ucsd.edu.

file:///C|/Users/Paul/Dropbox/Ece101_F16/Labs/Lab_1/Lab1_Supp.html[9/24/2019 4:27:22 PM]

Das könnte Ihnen auch gefallen