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

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

Introduction to MATLAB

Getting started with MATLAB

MATLAB TUTORIAL WORKSHEET

Lecturer: Keyvan Dehmamy

YOGYAKARTA STATE UNIVERSITY MATHEMATICS AND NATURAL SCIENCES FACULTY MATHEMATICS EDUCATION STUDY PROGRAM

Dr Richard Greenaway

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Matlab Introduction. Scalar Variables and Arithmetic Operators

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Computer Programming in MATLAB

Introduction to MATLAB

How to learn MATLAB? Some predefined variables

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

The value of f(t) at t = 0 is the first element of the vector and is obtained by

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

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

PC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.

Finding, Starting and Using Matlab

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

1 Introduction to MATLAB

Introduction to MATLAB

An Introduction to MATLAB II

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Introduction to MATLAB

1 Introduction to MATLAB

University of Alberta

VARIABLES Storing numbers:

Desktop Command window

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

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

AN INTRODUCTION TO MATLAB

Matlab Tutorial. Get familiar with MATLAB by using tutorials and demos found in MATLAB. You can click Start MATLAB Demos to start the help screen.

Introduction to MATLAB LAB 1

Introduction to Matlab

CITS2401 Computer Analysis & Visualisation

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

! The MATLAB language

EGR 111 Introduction to MATLAB

Stokes Modelling Workshop

MATLAB SUMMARY FOR MATH2070/2970

Introduction to Matlab

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Introduction to Matlab

Matlab Lecture 1 - Introduction to MATLAB. Five Parts of Matlab. Entering Matrices (2) - Method 1:Direct entry. Entering Matrices (1) - Magic Square

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

A Quick Tutorial on MATLAB. Zeeshan Ali

Introduzione a MatLab. Prof. Sebastiano Battiato

Getting Started with MATLAB

2.0 MATLAB Fundamentals

A Guide to Using Some Basic MATLAB Functions

9/4/2018. Chapter 2 (Part 1) MATLAB Basics. Arrays. Arrays 2. Arrays 3. Variables 2. Variables

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

Getting To Know Matlab

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

Getting started with MATLAB

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

Introduction to MATLAB programming: Fundamentals

Laboratory 1 Octave Tutorial

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Introduction to MATLAB

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

ARRAY VARIABLES (ROW VECTORS)

What is Matlab? A software environment for interactive numerical computations

MATLAB/Octave Tutorial

Chapter 1 Introduction to MATLAB

ECE 202 LAB 3 ADVANCED MATLAB

Chapter 1 MATLAB Preliminaries

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

Introduction to MATLAB

MATLAB Introductory Course Computer Exercise Session

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College

Digital Image Analysis and Processing CPE

Introduction to Unix and Matlab

Introduction to MATLAB

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

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

Introduction to Engineering gii

PART 1 PROGRAMMING WITH MATHLAB

LAB 1: Introduction to MATLAB Summer 2011

Dr Richard Greenaway

A GUIDE FOR USING MATLAB IN COMPUTER SCIENCE AND COMPUTER ENGINEERING TABLE OF CONTENTS

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

Matlab Tutorial: Basics

A General Introduction to Matlab

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1

1-- Pre-Lab The Pre-Lab this first week is short and straightforward. Make sure that you read through the information below prior to coming to lab.

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

Transcription:

Introduction ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah) MATLAB is a powerful mathematical language that is used in most engineering companies today. Its strength lies in its numerical analysis. MATLAB is not the fastest language to process large amounts of data, but it is certainly one of the cleanest. Everything in MATLAB is treated as an array, or more specifically a matrix. Matrix calculations and manipulations are greatly reduced with many inbuilt functions ready for use. Variables In MATLAB, variables can be assigned from the command prompt or assigned in m-files. To get a complete listing of all the variables, use the command >> who MATLAB is a fairly flexible language when it comes to naming variables. They can be declared at any time. Upon use of a variable it is considered declared and can be used thereafter. Most variables don t really have a type. They are usually a number or an array of numbers. It is best that all variables used are declared at the start of an m-file or function. That way no erroneous variables are created and the code is easier to debug. Variables must not contain spaces. The general rules for variables are: Variable Naming Rules Variable names are case sensitive. Variable names can contain up to 31 characters. Any characters beyond the thirty-first are ignored Variable names must start with a letter, followed by any number of letters, digits or underscores. Punctuation characters are not allowed, since many of them have special meaning to MATLAB Comment/Examples Cost, cost, CoST and COST are all different MATLAB variables. howaboutthisvariablename how_about_this_variable_name X51483 a_b_c_d_e In addition there are some MATLAB special variables: Special Variables ans pi eps Description Default variable name used for results Ratio of the circumference of a circle to its diameter Smallest number such that, when added to one, creates a number greater than one on the computer. Count of floating-point operations flops inf Stands for infinity (e.g. 1/0). NaN (or) nan Stands for Not-a-Number (e.g. 0/0). i (and) j i = j = -1 nargin nargout realmin realmax The semi colon character ( ; ) is used to suppress output Number of function input arguments used. Number of functions output argument used Smallest possible real number Largest useable positive real number.

File Navigation All the DOS/UNIX commands work in MATLAB. These can be used to navigate the directory structure in which the files are stored. Some typical commands are: Command ls dir cd cd <directory> pwd Description Directory and file listing Directory and file listing Print current directory Change directory Print working directory For a complete listing type >> help general at the command prompt. MATLAB Help If you can t remember the exact syntax for a function, or whether sin() takes in arguments in radians or degrees, then the MATLAB help resource is for you. For help on a specific function, at the command prompt type >> help <function name> and the help file will be displayed. Alternatively, the MATLAB toolboxes can be browsed using the help menu at the top of the screen. Go to Help -> Help Window to browse the various toolboxes. Usually if you think that there is a mathematical function, then it is probably useful to do a help command on it as in most cases it will exist. Arrays and Array Operations Arrays, or vectors, can be declared in a multitude of ways. The easiest way to create an array is to specify the elements: >> x = [0 0.1*pi 0.2*pi 0.3*pi 0.4*pi 0.5*pi 0.6*pi 0.7*pi 0.8*pi 0.9*pi pi]; This creates a row vector with 11 elements in it. MATLAB arrays are a bit unusual to arrays in other languages in that they start from element 1. Hence» x(1) ans = and 0» x(0)??? Index into matrix is negative or zero. See release notes on changes to logical indices. Another way to specify an array is to use the colon ( : ) operator. It works as: Variable = (start_value : step size : _value ); So y = (0:0.1*pi:pi);

does exactly the same thing as the array declared above. Array concatenation is relatively straight forward. You just get two arrays and enclose them in square brackets. >> A = [1 2 3 4]; >> B = [5 6 7 8]; >> C = [A B] C = [1 2 3 4 5 6 7 8] Transpose of an array is achieved using the ( )» C = C' C = 1 2 3 4 5 6 7 8 To do a scalar operation on an array, just use the normal mathematical operations. For example to multiply every element in C by 2, you use the command: >> C = 2*C C = 2 4 6 8 10 12 14 16 Say you would like to multiply every element in a by every element in b. Then you would have to use the (. ) operator. It applies the statement element-wise, performing the operation on each term in one vector by the corresponding term in the other. If the dot operator wasn t used then MATLAB would assume that you wanted to do a matrix manipulation and then change the vectors in the linear algebra fashion. An example of this is as follows:» a = [2 2 2 2] a = 2 2 2 2» b = [1 2 3 4] b =» a.*b ans = 1 2 3 4 2 4 6 8

If a*b was used, the result would have been» a*b??? Error using ==> * Inner matrix dimensions must agree. This was because MATLAB was trying to perform a matrix calculation on the data, which cannot be done in this case as two row vectors cannot be multiplied in matrix form. To access elements in a matrix is the same way as it is done for a vector. Say that M is a 5x5 matrix. To access the (1,4) element, the command is >> M(1,4) There are some MATLAB commands that make creating vectors easy. Two of the more useful ones are >> zeros(n,m); >> ones (n,m); Zeros creates a matrix (n,m) made entirely of zeros. This can be used to initialize matrices or to setup an impulse vector. Ones, on the other hand, returns a (n,m) matrix composed entirely of ones. This is useful for some FIR filter realizations. Polynomials Polynomials in MATLAB are represented by arrays. The usual representation is that the elements in an array are the coefficients of the polynomial starting from the highest order term to the lowest order term. If a term is not present then its coefficient is entered as 0. An example is: is represented by >> y = [5 0 9 1]; The other way to represent polynomials is via their roots. In MATLAB these are also represented by arrays. The polynomial: is represented by >> y = [-3 5-9]; y. 5x 3. 9x 1 y ( x 3 ).( x 5 ).( x 9) The more common representation is the first one but either is used deping upon the application. Two very useful commands are roots and poly. The command roots() will factorize a polynomial into its roots and return the roots in an array. The function poly() does the opposite. It takes in the roots of a polynomial and returns the coefficients of the polynomial. To multiply two polynomials, you have to use the conv() command. This multiplies two arrays in the polynomial sense and returns the resultant polynomial Programming loops. All the usual programming loops can be implemented in MATLAB. If statements, while and for loops can all be implemented with the following syntax. if statement: - syntax

Statement syntax if <case> elseif <case> else if x > 10 y = y + 1; elseif x > 5 y = y 1; else y = y 4; Example while loops Statement syntax while <case> while x < 20 y = y/3; x = x + 1; Example For loops Statement syntax for <variable = statement> for n = 1:1:10 x(n) = 2*n; Example M-files and Functions Instead of writing command line parameters in MATLAB, a text file can be assembled of commands. These are called m-files because the files are named <filename>.m (m standing for MATLAB). MATLAB has a text editor in which you can create and save m-files. You place code in an m-file as you would at the command prompt and upon calling the script the code executes sequentially. To execute an m-file, change to the directory in which it is located and type the name of the file. For example if there is an m-file called lab1.m in the current directory execute it by typing at the command prompt: >> lab1 If commands are placed into an m-file and it is executed, the variables created and used go into the MATLAB workspace and for all intents and purposes can be treated as global variables. To restrict a cluttering up of the workspace, functions can be created. Create an m-file as usual but at the start use the keyword function with this syntax. function [output1,output2, ] = functionname(input1,input2, ) Save the m-file with the same name as functionname and then the function may be called from the command prompt as you would any other function. Functions obey the scope and privacy laws of most programming languages. So any variables declared within the function are local and disappear upon exiting the function. The only things returned to the workspace are the outputs of the function. Plotting One of the most useful abilities of MATLAB is its ability to plot data easily. To plot a vector type >> plot(vectorname)

at the command prompt and a scaled plot of the vector appears. There are a lot of inputs to plot to make the plot nicer looking so type help plot at the command prompt to find the usefulness of plotting. Another useful plot for discrete data is stem(). It will plot a discrete plot for you that is sometimes more illustrative. To clear the graph type clf. Plots can be manipulated easily. Titles, x-labels, and y-labels can be added by in the following manner: >> title( Frequency Curve ); >> xlabel( Frequency (Hz) ); >> ylabel( Amplitude (Volts) ); More than one graph can be plotted at the one time. The subplot(n,m,x) command does this and takes in arguments (n,m) which are the number of axes to display i.e. (3,2) gives six axes, three down and two across. The final argument to subplot is which graph is currently being referred to. This is best illustrated with an example. The following is a snippet of MATLAB code and its corresponding output. % initialize variables t = (0:0.01:3); x = 3*sin(2*pi*t); y = 4*cos(2*pi*t); % plot the sine wave in the top graph subplot(2,1,1),plot(t,x); subplot(2,1,1),title('sine wave (frequency 1Hz)'); subplot(2,1,1),xlabel('time (sec)'); subplot(2,1,1),ylabel('amplidtude (Volts)'); %plot the cos wave in the bottom graph subplot(2,1,2),plot(t,y); subplot(2,1,2),title('cos wave (frequency 1Hz)'); subplot(2,1,2),xlabel('time (sec)'); subplot(2,1,2),ylabel('amplidtude (Volts)'); 4 Sine wave (frequency 1Hz) Amplidtude (Volts) 2 0-2 -4 0 0.5 1 1.5 2 2.5 3 Time (sec) Cos wave (frequency 1Hz) 4 Amplidtude (Volts) 2 0-2 -4 0 0.5 1 1.5 2 2.5 3 Time (sec)