ECE 202 LAB 3 ADVANCED MATLAB

Similar documents
Introduction to MATLAB LAB 1

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

Introduction to MATLAB

A Guide to Using Some Basic MATLAB Functions

8. Control statements

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

function [s p] = sumprod (f, g)

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

Dr. Iyad Jafar. Adapted from the publisher slides

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

Desktop Command window

What is Matlab? A software environment for interactive numerical computations

Introduction to MATLAB

Introduction to MATLAB

Laboratory 1 Octave Tutorial

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

MATLAB Guide to Fibonacci Numbers

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Table of Contents. Introduction.*.. 7. Part /: Getting Started With MATLAB 5. Chapter 1: Introducing MATLAB and Its Many Uses 7

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Basic Plotting. All plotting commands have similar interface: Most commonly used plotting commands include the following.

Page 1 of 7 E7 Spring 2009 Midterm I SID: UNIVERSITY OF CALIFORNIA, BERKELEY Department of Civil and Environmental Engineering. Practice Midterm 01

MATLAB Introduction to MATLAB Programming

ENGR 1181 MATLAB 09: For Loops 2

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction to MATLAB

EE3TP4: Signals and Systems Lab 1: Introduction to Matlab Tim Davidson Ext Objective. Report. Introduction to Matlab

MATLIP: MATLAB-Like Language for Image Processing

Practical 4: The Integrate & Fire neuron

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Additional Plot Types and Plot Formatting

Introduction to Matlab

AN INTRODUCTION TO MATLAB

Introduction. C provides two styles of flow control:

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Lab 0a: Introduction to MATLAB

Introduction to MatLab. Introduction to MatLab K. Craig 1

C++ Programming: From Problem Analysis to Program Design, Third Edition

Introduction to MATLAB

INTRODUCTION TO MATLAB

lab MS Excel 2010 active cell

Programming for Experimental Research. Flow Control

Why Is Repetition Needed?

QUICK INTRODUCTION TO MATLAB PART I

Our Strategy for Learning Fortran 90

What is MATLAB and howtostart it up?

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

Repetition Structures Chapter 9

Dr Richard Greenaway

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

Finding MATLAB on CAEDM Computers

PROGRAMMING WITH MATLAB WEEK 6

MATLAB Introductory Course Computer Exercise Session

REPETITION CONTROL STRUCTURE LOGO

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

SPARK-PL: Introduction

Introduction to Matlab

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Computer Programming in MATLAB

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

FDP on Electronic Design Tools - Computing with MATLAB 13/12/2017. A hands-on training session on. Computing with MATLAB

EE 1105 Pre-lab 3 MATLAB - the ins and outs

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

Some elements for Matlab programming

Unix Computer To open MATLAB on a Unix computer, click on K-Menu >> Caedm Local Apps >> MATLAB.

Dr Richard Greenaway

Language Fundamentals

KaleidaGraph Quick Start Guide

Chapter 4 C Program Control

Lab 7 (All Sections) Prelab: Introduction to Verilog

ECE Lesson Plan - Class 1 Fall, 2001

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

MATLAB SUMMARY FOR MATH2070/2970

MATLAB Second Seminar

Nuts & Bolts guide to MATLAB

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

WINTER 2017 ECE 102 ENGINEERING COMPUTATION STANDARD HOMEWORK #3 ECE DEPARTMENT PORTLAND STATE UNIVERSITY

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

MATLAB Project: Getting Started with MATLAB

Microsoft Excel. Charts

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

YOLOP Language Reference Manual

Armstrong Atlantic State University Engineering Studies MATLAB Marina 2D Plotting Primer

Introduction to programming in MATLAB

Chapter 3: Rate Laws Excel Tutorial on Fitting logarithmic data

7 Control Structures, Logical Statements

Boolean Logic & Branching Lab Conditional Tests

Chapter 3: Programming with MATLAB

GUI Alternatives. Syntax. Description. MATLAB Function Reference plot. 2-D line plot

The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development

3 The L oop Control Structure

Transcription:

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.