Version 1.2 1 of 13 BEFORE YOU BEGIN PREREQUISITE LABS ECE 201 Labs EXPECTED KNOWLEDGE ECE 202 LAB 3 ADVANCED MATLAB Understanding of the Laplace transform and transfer functions EQUIPMENT Intel PC with access to MATLAB and the signal processing toolbox MATERIALS Formatted 1.44 3¼ floppy diskette (optional) Speakers Speaker Control Box OBJECTIVES After completing this lab you should be more familiar with MATLAB. Specifically, you should be able to write your own MATLAB scripts and functions and know how to use some of the functions provided in the signal processing toolbox. INTRODUCTION MATLAB has many tools to assist in the development of signal and systems. These tools include functions that allow you to listen to signals and save signals as audio files. There are also many tools that allow you to display see signals in many different forms. MATLAB also has tools to help design and test analog and digital filters. PRELAB Throughout this lab you will be asked to create many plots and images. By now, you should be familiar with how to title and label plots in MATLAB. You must label and title all plots and images turned in with your lab worksheet, even if you are not specifically told to do so. Answer Questions 1 2.
Version 1.2 2 of 13 PROGRAMMING THE MATLAB EDITOR MATLAB provides its own text editor that can be used to create and edit script files. To open the MATLAB editor, use the EDIT command at the command prompt. The editor may also be opened form the menu toolbar by selecting File New M-file. MATLAB script files are saved with the extension.m. SCRIPT FILES As you become more familiar with MATLAB, you will find it helpful to store lengthy sequences of commands in a single file that can be edited and run multiple times. These files are called MATLAB scripts. They are ASCII text documents that contain MATLAB commands. The commands are typed in the file exactly as they would be typed at the command prompt and are executed in the order that they appear from top to bottom. All of the general commands are supported and MATLAB has commands and structures designed specifically for use in script files. Script File Template As with other programming languages, you should always document your source code with comments. Comments are ignored by the programming language compiler (or interpreter) and are denoted in MATLAB with the percent sign (%). Script files that you turn in with your lab reports need to contain a heading that documents your name, the lab number, the lab title, and the date that the work was completed. Following the heading should be a few comment lines that describe what tasks the script file performs. After the heading and program description, the variables that are to be used in the script file are declared and commented. Large scripts should be broken up into sections. Each section should contain comments describing what actions are being performed. These comments will assist you during debugging and will help others understand your script. Any variables declared in the script file stay resident in memory after the script file has executed. The variables in script files are global, which means they may be accessed outside of the script file. Scripting Commands MATLAB provides many commands and structures that may be used in script files. FOR Loop The FOR loop is used to run through a block of code a specific number of times. The syntax for the FOR loop is:
Version 1.2 3 of 13 for counter = start:stop statements to be executed where counter is any legal variable name start specifies the starting value, usually an integer stop specifies the ing value, usually an integer indicates the of the for block All lines of code between the FOR and END commands are indented. Though this indentation is not required, it is recommed because it improves readability and makes debugging easier. The first time through the loop, the variable counter is assigned the value of start. At the of the executable statements, counter is incremented by one. This process is repeated until counter is less than or equal to stop. For example, to the code for a FOR loop to iterate ten times would be for count = 1:10 By default, MATLAB increments the loop counter by 1 each time through the loop. To change the default increment, the FOR command uses the syntax for count = start:incr:stop where incr is the new increment The command for count = 1:.5:10 increments count by.5, thereby causing 20 iterations of the loop. WHILE Loop The WHILE loop is similar to the FOR loop in that it is used to repeatedly execute a block of code. The WHILE loop differs in that it uses a conditional statement to exit the loop. The syntax for a WHILE loop is while <condition is true> statements to be executed As long as the condition is true, the program will remain in the loop. The condition is usually a comparison with a relational operator. Some examples are: x > 0 y <= z (a > 0) & (a < 20)
Version 1.2 4 of 13 Another difference in the WHILE loop is that the conditional value must be edited within the loop statements. Given the following code: while x < 10 y = [y x + 3]; x = x + 0.1; the program will continue to loop until x is no longer less than 10. In this example, the last time the program loops is when x = 9.9. When x = 10, x is no longer less than 10 (x < 10 is false) and the loop is exited. If the line x = x + 0.1 was omitted, x would remain equal to its original value of 1. Since 1 is always less than 10 the loop would never be exited. This is called an infinite loop. BREAK The break command terminates the execution of FOR and WHILE loops. IF, ELSEIF, and ELSE The IF statement is used to execute a segment of code only if specified conditions are true. The syntax for the IF statement is: if <condition is true> statements to execute If the condition is true, the code immediately following the IF statements is executed. If the condition is false, the code is skipped. The ELSE statement is used in conjunction with the IF statement to execute a block of code if the condition equates to false. The syntax for the IF ELSE statement is: if <condition is true> execute this statement else execute this statement For example, consider the function f(x) = x + 1 for x 0 1 for x < 0 To determine the value of f(x) you would use the following IF ELSE statements: if x >= 0 y = x + 1 else y = 1
Version 1.2 5 of 13 In the cases where there are three or more choices, the ELSEIF statement may be used in conjunction with the IF ELSE statements. The syntax for the IF ELSEIF ELSE structure is: if <condition> statements elseif <condition> statements else statements The statements after the ELSEIF command are executed only if its condition is true and if all previous IF and ELSEIF conditions are false. EXAMPLE SCRIPT FILE The following is a script file that prompts the user for an integer and determines if the integer is a prime number. % John Smith % ECE 202 Lab 3 % Advanced MATLAB % 23 June 2000 % % This script file determines if a number entered by the user is a prime number. % The number is first tested to see if it is greater than one. By definition, one % is neither a prime number nor a composite number. If the number is greater than one % it is tested to see if it is equal to two. Two is the first prime number (and the % only even prime number). If the number is not two, the number is divided by all the % numbers between two and the square root of the number. If the number is not equally % divisible by all the numbers between two and its square root then the number is prime. % % Variables % % number Number to test % flag Set to 1 if number is prime, 0 if number is not prime % sqr_root Square root approximation of number % count Used as variable in FOR loop % Prompt user for number to test number = input('enter number to test for prime: '); % Test to see if number is less than or equal to 1 if number <= 1 flag = 0; % Set flag to 0 elseif number == 2 % Test to see if number is equal to 2 flag = 1; % Set flag to 1 else % Test to see if number is prime flag = 1; % Assume number is prime. Value will be change if test fails. % Calculate the square root of number and round down to nearest integer.
Version 1.2 6 of 13 sqr_root = fix(sqrt(number)); % Loop to divide number by all numbers between 2 and the square root of number for count = 2:sqr_root if rem(number,count) == 0 % Test remainder value for number divided by count. % If remainder equals 0, then number is not prime. flag = 0; % Set flag to 0 break; % Break out of FOR loop ; % End of nested IF block ; % End of FOR loop ; % End of IF ELSEIF ELSE block % Display results deping of value of FLAG if flag == 1 fprintf('\n%i is prime.\n',number) else fprintf('\n%i is not prime.\n',number) ; Answer Question 3. Notice that a percent sign (%) was used for all of the descriptive information given at the beginning of the file. If you type help prime at a MATLAB prompt, it will return all of the comments at the beginning of the file until a line is encountered that does not begin with the comment character, %. FUNCTIONS Functions are like script files that can take arguments and return values. The first line of a function, or the declaration line, must contain the keyword FUNCTION. The syntax for FUNCTION is: function r = function_name(x) where r is the value returned by the function function_name is the name of the function x is the input argument A function that is going to return two or more values needs to have the output variables enclosed in square brackets ([]). function [mag, phase] = complex_num(x) A function with more than one input argument must list all of the arguments within parenthesis, seperated by a comma: function v = volumn(x,y,z) The lines following the function delcaration line should be comments describing the function. These are the lines that are displayed when the user types help function_name at the command
Version 1.2 7 of 13 prompt. The HELP command will display all the comment lines, starting with the line after the declaration line, until a non-comment line is encountered. The variables used in functions are local only to that function. Unlike variables declared in script files, variables declared in functions are only accessible by the function and are not kept in memory after the function has terminated. EXAMPLE FUNCTION FILE The following is a function that determines the heavside (unit step) values. function signal = heavside(time) % This function creates a vector signal that is the same length as vector time. % The values of the signal are zero when the values of time are negative. % The values of signal are one when the values of time are positive. % This is equivalent to the unit step. signal = zeros(size(time)); % Create signal with all zeros non_zero = find(time > 0); % Find elements of time greater than zero % Assign one to the elements of signal that correspond to the elements % of time that are positive. signal(non_zero) = ones(size(non_zero)); Answer Question 4. COMPLEX NUMBERS MATLAB stores and displays complex numbers in the same way you would find them in a text book. To enter the complex number 3 + 4i you would enter» 3 + 4i MATLAB also allows the use of j instead of i to represent complex numbers.» 3 + 4j Complex numbers may also be entered as» 1 + i*2» 7 + j*1 Complex numbers can also be assigned to variables, vectors and matrixes.» x = 2 +i;
Version 1.2 8 of 13» y = [5 + 3j, 5-3j];» Z = [3 + 3j, 3-3j;1 + 2j, 1-2j]; It is a good practice not to use i or j as variable names, especially if you are using complex numbers. Answer Questions 5 7. PLOTTING MATLAB has many tools that allow you to plot data in different ways. You should already be familiar with the MATLAB PLOT command. Here you will be introduced to other methods for plotting data. THE SUBPLOT COMMAND MATLAB enables you to add multiple plots to a figure window with the SUBPLOT command. The syntax for SUBPLOT is subplot(m,n,p) where m is the number of rows n is the number of columns p is the pth window, counted from left to right and top to bottom. For example, to create a figure with four plots, two across and two down, the command would be subplot(2,2,1) To plot data in the lower left plot, the commands would be subplot(2,2,3) plot(data) LOGARITHMIC PLOTS MATLAB has three commands that allow data to be plot on a variety of logarithmic plots: SEMILOGX, SEMILOGY, and LOGLOG. The commands take the same arguments as the PLOT command, but differ in the following ways: SEMILOGX uses a logarithmic scale for the abscissa (x-axis). SEMILOGY uses a logarithmic scale for the ordinate (y-axis). LOGLOG uses logarithmic scales for both the abscissa and the ordinate.
Version 1.2 9 of 13 THE GRID COMMAND The GRID command turns the gridlines of the selected plot on and off. To turn the grid on you would use the command grid on To turn the grid off grid off The GRID command by itself can be used to toggle the grid on and off. THE LEGEND COMMAND The leg command puts a leg on the current plot. The simplest form of the command is leg( string_1, string_2, ) where the strings specify the labels for the curves on the plot. To place the leg in a specified location the syntax would be leg(,n) where N is an integer value from -1 to 4, which places the leg in the following locations: -1 To the right of the plot 0 Automatic placement of least conflict with data. 1 Upper-right corner. 2 Upper-left corner. 3 Lower-left corner. 4 Lower-right corner. The leg may also be moved by dragging it to the desired location. A label in the leg can be edited by double clicking on it. To remove the leg from the plot the syntax would be leg off Answer Questions 8 14. THE STEM COMMAND The STEM command plots the individual data points with perpicular lines, or stems, connecting the data point to the abscissa. The syntax for the STEM command is stem(x,y) stem(x,y, filled )
Version 1.2 10 of 13 stem(x,y, string ) The first option s each stem with an open circle, and the second option s each stem with a filled circle. The third option has a string as a third argument. The values in the string determine the line type, symbol and color. Refer to the PLOT command for more information on valid line types. THE BAR COMMAND The BAR command plots the data as a bar graph. The syntax for the BAR command is bar(x,y) bar(x,y, string ) The argument string is a single character that determines the color of the bar graph. Refer to the PLOT command for information on valid color values. THE STAIRS COMMAND The STAIRS command creates a stair step plot. The syntax for the stair command is the same as for the BAR command. Answer Questions 15 19. CHANGING PLOT PROPERTIES You should already be familiar with MATLAB s GET and SET commands. These commands can be used to change the property values of plots. The properties of plots may also be changed by using the tools available from the Tools menu in the figure window. With these tools you can change the properties of the axes, lines and text that appear in the figure. The tools are enabled from the Tools menu by selecting Enable Plot Editing. EDITING THE AXES PROPERTIES To edit the axes properties, first click on the axes of the plot, then from the Tools menu, select Axes Properties. The Edit Axes Properties dialog box will open, as displayed in Figure 1. From this dialog box, you may enter a title, labels, change the axis scale to linear or logarithmic, change the limits of the axes, change the number of tick marks, and turn on or off the grid lines for a given axis.
Version 1.2 11 of 13 EDITING LINE PROPERTIES Figure 1. Edit Axes Properties Dialog Box. To edit the line properties, first click on the line (curve) to edit, then from the Tools menu, select Line Properties. The Edit line Properties dialog box will open, as displayed in Figure 2. You can change the line width, style and color, and the marker size and symbol. Figure 2. Edit Line Properties Dialog Box.
Version 1.2 12 of 13 EDITING TEXT PROPERTIES To edit the properties of any text in the figure, click on the text you want to change, then from the Tools menu, select Text Properties. The Edit Font Properties dialog box will open, as displayed in Figure 3. You can change the font, style and size of any text just as you would in any Windows program. Answer Questions 20 29. AUDIO TOOLS Figure 3. Edit Font Properties Dialog Box. MATLAB comes with a set of audio tools that allow you to listen to, save, record, and load signals and Microsoft WAV (.wav) sound files. THE SOUND COMMAND The SOUND command plays a vector as a sound. Signals can be represent as vectors, such as the declaration» t = 0:0.001:5;» y = sin(100 * pi * t); The syntax for the SOUND command is sound(y) sound(y,fs) sound(y,fs,bits)
Version 1.2 13 of 13 where y is the vector representing the signal Fs is the sampling frequency (the number of elements of vector y played per second) bits is the bits per sample If Fs is omitted, as in the first option, SOUND uses a sampling frequency of 8192 Hz. THE SOUNCSC COMMAND The SOUNDSC command is the same as the SOUND command except that the data is scaled so that the sound is played as load as possible without clipping. Answer Questions 30 33.