You are on page 1of 12

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

Chapter 1.

Introduction to MATLAB
What is MATLAB?
MATLAB (MATrix LABoratory) is a computer language for technical computing, mathematical analysis, and system simulation. It is an interactive tool and is specifically designed to solve problems in the engineering fields, sciences, and business applications. MATLAB can be used for Mathematical computations Modeling and simulation of systems Data (signal) analysis and processing Visualization and graphics and Algorithm development.

MATLAB is an interactive system whose basic data element is a matrix ( an array ). It provides a collection of application-specific solutions called toolboxes.

The MATLAB System:


The following major parts of MATLAB system are widely used. Desktop Tools and Development Environment: This is the set of tools and facilities that help user to use MATLAB functions and files. It includes the MATLAB desktop and Command Window, a command history, an editor and debugger, a code analyzer and other reports, and browsers for viewing help, the workspace, files, and the search path. The MATLAB Mathematical Function Library: This is a vast collection of computational algorithms. The comprehensive collections of MATLAB functions (Mfiles) that extend the MATLAB environment to solve particular classes of problems are called Toolboxes. These MATLAB functions (M-files) are ranging from elementary functions, like sum, sine, cosine, and complex arithmetic, to more sophisticated functions to solve problems of science and engineering. Areas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others. The MATLAB Language: This is a high-level matrix/array language whose basic data element is a matrix (array).The language has control flow statements, functions, data structures, input/output, and object-oriented programming features.
1

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

That is data variable can be directly assigned a value of any data type. It does not require dimensioning. That is it is not required to declare the type and dimension of the variable. This simplifies solving many technical computing problems, especially those with matrix and vector formulations. It allows to rapidly create quick and dirty throw-away programs. That is it is possible to do calculations one line at a time at the command line using the same syntax as would be used in a file. Matlab also provides to create large and complex application programs. It's even possible to write loops and branches at the command line if you want to! Of course this would lead to a lot of wasted effort a lot of the time, so doing anything beyond very simple calculations, testing to see if a certain function, syntax, etc. works, or calling a function you put into an .m file should be done within an .m file MATLAB is interesting in that it is dynamically compiled. We know that when the programming languages like C or C++ are used, the code is compiled by explicitely running through a compiler to generate an execuable file and run the executable file to obtain a result. But in Matlab the code is neither run through a compiler nor a execuable file is created. Instead, MATLAB simply goes line by line and performs the calculations without the need for an executable. Graphics: MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications. MATLAB External Interfaces:This is a library that allows you to write C and Fortran programs that nteract with MATLAB. It includes facilities for calling routines from MATLAB dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

Starting MATLAB:
It is assumed that the software is installed on the computer. The user can start the MATLAB by clicking on the icon on the desktop and the MATLAB desktop window opens.

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

The default view of the various windows of MATLAB contains the four smaller windows: The Command Window: The Command Window is MATLAB's main window and can be used for executing commands, opening other windows, running programs written by the user, and managing the software. The Current Directory Window: MATLAB file operations use the current directory and the search path as reference points. Any file you want to run must either be in the current directory or on the search path. The Workspace Window: The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory. The Command History Window: Statements you enter in the Command Window are logged in the Command History. From the Command History, you can view and search for previously run statements, as well as copy and execute selected statements.

Working In The Command Window


Once we get into MATLAB, we meet a prompt >> called the MATLAB prompt. This prompt receives a user command and processes it providing the output on the next line. The command clc clears the Matlab command window and moves the cursor to the top of that window. Defining Scalar Variables
3

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

MATLAB allows you create variables on the fly. A variable is a name that is
assigned a numerical value which can be used in mathematical expressions, in functions, and in any MATLAB statements and commands. A variable is actually a name of a memory location. In MATLAB the = sign, called the assignment operator assigns a value to a variable. Enter the following on command (prompt is also variable named x. >> x = 10 ENTER MATLAB responds to the entry as x= 10 Note that MATLAB just considers scalars as 1 x 1 matrices. The variables created can be cleared(deleted) by using the function clear. >>clear ENTER Removes all defined variables from memory. >>clear variable_name Can clear a single variable named variable_name. shown) to assign a value 5 to a

Matlab As A Computational Tool


Matlab can be used to evaluate any expressions.This is achieved by simply entering the mathematical expression at the command prompt. >> 2 + 6 - 5 ENTER

MATLAB responds with


ans = 3 In the above expressions no variable is defied.The result of evaluation of an expression is assigned to a default variable ans (short form of answer).We can make use of the result using the default variable.For Example >>ans/3 ENTER

MATLAB responds with


ans = 2.500 The basic arithmetic operators used in MATLAB are +, -, *, exponents (powers): 2^4=16.
4

/, ^ and these are used in

conjunction with brackets: ( ). The symbol * is for multiplication and ^ is used to get

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

Matlab works according to the priorities: 1. quantities in brackets, 2. powers 3. * or /, working left to right 4. + -, working left to right >> 2 + 3/4*5 ans = 5.7500 ENTER ( Example: 2 + 3^2 2 + 9 = 11) ( Example: 3*4/5 12/5), ( Example: 3+4-5 7-5),

Thus the evaluation of the matlab expression is 2 + (3/4)*5 by priority 3 and not 2 + 3/(4*5) and Matlab responds with

Creating Matrices
The basic data element in MATLAB is a matrix. A scalar in MATLAB is a 1x1 matrix, and a vector ( array ) is a 1x n (or n x 1) matrix. To create an array of 4 elements say x={ 3,5,7,9} type >> x= [3, 5, 7, 9] The response is x= 3 5 7 9 The elements of array are written within square brackets [ comma or a space. The : (colon) operator is used to create a vector (array). The general format of a command to generate array is Starting value : Increment : Maximum value that the variable can take To create a vector with elements between 0 and 20 evenly spaced in increments of 2. (this method is frequently used to create a time vector): >> y = 0:2:20 y= 0 2 4 6 8 10 12 14 16 18 20 With the default increment 1, the format reduces to Starting value : Maximum value that the variable can take To generate an array of elements whose values range from 1 to 4 i.e., {1, 2, 3, 4} >> y = 1:4 ENTER Generates the array and outputs y= 1234
5

ENTER

] and are separated by

ENTER

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

In case of multi dimensional arrays (m X n matrix) the rows are separated by semi colon. For example, create a 3x3 matrix A that has [2 ,4, 6] in the first row,[ 1, 3, 5] in the second row, and 3s in the third row: >> A = [2 4 6; 1 3 5; 3 3 3] MATLAB responses with A= 246 135 333 To access a particular element of matrix A: say from 1st row 2nd column. >> A(1,2) ans = 4 The : (colon) operator is used to access all the elements of a row or column. To access a particular row of A: say complete 2nd row >> A(2,:) ans = 135 Suppressing Output with Semicolon (;) It is useful to have MATLAB print the results of the calculations. In computations having multiple statements the intermediate results need expression on the right hand side is terminated with a semicolon. >> y = 6; ENTER Note the colon (;) in the expression and Observe that nothing is displayed following the entry. But obviously, MATLAB does keep the value in memory. To see this type >> y ENTER Response is y= 6 Note that the colon (;) is removed in the expression and the value that was stored in variable y is displayed following the entry.
6

ENTER

The semicolon is used here to separate rows in the matrix.

ENTER

ENTER

Returns 2nd row of A as

not be

displayed.MATLAB will print the result of every assignment operation unless the

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

In case of the entry >> A = [1 1 1; 2 2 2; 3 3 3]; ENTER Matrix A has been created but MATLAB doesnt display it. The semicolon is necessary when youre running long scripts and dont want everything written out to the screen! Unlike C or C++ Semicolon (;) at the end of statement is NOT a MUST in MATLAB.

Functions
The MATLAB application is built around the MATLAB language .In addition to basic arithmetic operations, expressions in MATLAB can include functions. MATLAB has a very large library of built-in functions. A function has a name and an argument in parentheses. For example, the function that calculates the square root of a number is sqrt(x). Its name is sqrt, and the argument is x. When the function is used, the argument can be a number, a variable that has been assigned a numerical value. >>sqrt(36) Returns ans= 6 >>x = 49; sqrt(x) Returns ans = 7 Commonly used constants such as pi, and i or j for the square root of -1, are also incorporated into Matlab. The help command provides the information about the usage of any existing command. The general format is >> help [function name] For example >>help sin Returns the descreption of the usage of the function sin. The function lookfor finds all functions in all directories that might have something to do with a given key word. For example to find out the function which performs inverse of a matrix type >> lookfor inverse Lists at least a dozen matches,including the required function inv. DOC command displays the HTML documentation for the MATLAB function. >> doc sin
7

ENTER

ENTER

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

Displays HTML documentation for the function sin in the Help browser.

Plotting
One thing we want to do to with functions is plot them. It is also easy to create plots in Matlab. For example, to plot f as a function of t, type plot(t,f). A new window will come up with a plot of f(x) as a function of x. To plot a sine wave as a function of time. First make a time vector (the semicolon after each statement tells Matlab we don't want to see all the values) >> t=0:0.25:8 Compute the sin value at each time. t=
Columns 1 through 11 0 0.2500 0.5000 0.7500 1.0000 1.2500 1.5000 1.7500 2.0000 2.2500 2.5000 5.2500 8.0000 Columns 12 through 22 2.7500 5.5000 3.0000 5.7500 3.2500 6.0000 3.5000 6.2500 3.7500 6.5000 4.0000 6.7500 4.2500 7.0000 4.5000 7.2500 4.7500 7.5000 5.0000 7.7500 Columns 23 through 33

>> y = sin(t) y=
Columns 1 through 11 0 0.2474 0.4794 0.6816 0.8415 0.9490 0.9975 0.9840 0.9093 0.7781 0.5985 Columns 12 through 22 0.3817 0.1411 -0.1082 -0.3508 -0.5716 -0.7568 -0.8950 -0.9775 -0.9993 -0.9589 -0.8589 0.2151 0.4500 0.6570 0.8231 0.9380 0.9946 0.9894 Columns 23 through 33 -0.7055 -0.5083 -0.2794 -0.0332

plot the computed values >> plot(t,y) Opens the figure

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

To plot a discrete sequence or "stem" plot function stem can be used. This plots the data sequence as stems from the x axis terminated with circles for the data value. For example To plot a sequence y=[10 4 5 7 8] define the sequence >> y=[10 4 5 7 8] y= 10 4 5 7 8 Definee the time index >> n = [0:4] n= 01234 Now plot the sequence >>stem(n,y) Opens the figure

Matlab has many features for plotting. To label the figure which indecates the axes use xlabel and ylabel functions. To define the x-axis, type >> xlabel(x ---- >) Creates a label on the x-axis. To define the y-axis type ylabel(f(x)--- >).This creates a label on the y-axis. To place a title on the graph the command title(Function f) can be used. The function axis is used to control axis scaling and appearance. axis([XMIN XMAX YMIN YMAX]) sets scaling for the x- and y-axes on the current plot. >> axis ([-1,10,-1,11]) Sets the x axis scale from -1 to 10 and y axis scale from -1 to 11

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

Using several graph windows The function figure can be used to create a new figure window. Multiple figure windows can be opened for different plots. Plotting several axes in the same graph window The subplot function breaks the Figure window into m X n (read as m-by-n) sub windows, selects the p-th sub window for the current plot. The axes are counted along the top row of the Figure window, then the second row, etc. For example, subplot (3,2,n) divides figure in to 3 rows 2 columns and selects the figure n for the plot of the function using plot or stem. (n can take values 1 to 6 (i.e, 3 x 2) ;only one at a time and only selected portion of the figure will be active)

>>subplot(3,2,4) >> stem(x,y) Will result in plot of the function at position with figure number 4.

10

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

The close all command closes all figures. PROGRAMMING IN MATLAB

M-files: Scripts and functions


To do computations of any significant length, it is required to construct long (and sometimes complex) sequences of statements. This can be done by writing the commands in a file and calling it from within MATLAB. Such files are called m-files because they must have the filename extension .m (for example, program1.m). Comments can be added to m-file, by putting a % at the beginning of a comment line. Anything after % is ignored until a new line. Use this to make your code readable document it for yourself and others! There are two types of m-files: script files and function files. Script files contain a sequence of usual MATLAB commands that are executed in order. Function files are the user defined functions that can be used as commands that often have input and output. Commands for specific problems can be created. These functions will have the same status as other MATLAB commands. Editor/ Debugger Use the Editor/Debugger to create and debug M-files. The Editor/Debugger provides a graphical user interface for text editing, as well as for M-file debugging. To create or edit an M-file use File > New or File > Open.

The editor can also be opened through the command edit.


11

Introduction to MATLAB for DSP

Nagaraja N S.,SSE,Mangalore

>> edit program1.m Running M-Files

ENTER

In the Editor/Debugger, to run a script M-file, or a function M-file that requires no input arguments, click the Run button on the toolbar. The button's tooltip includes the name of the file to be run, which is useful when you have more than one file open. Alternatively, select Debug > Run filename.

If the file is not in a directory on the search path or in the current directory, you can either change the current directory to the directory containing the file, or you can add the directory containing the file to the search path.(Is to be done in command window.) If the file has unsaved changes, running it from the Editor/Debugger automatically saves the changes before running. To run the script file from the command prompt simply type the name of the m-file >> program1 ENTER The program runs. INPUT Prompt for user input. The input command gives the user the prompt in the text string and then gives the user the prompt in the text string and then waits for input from the keyboard. waits for input from the keyboard. >> R = INPUT(Enter the Number : -) Displays the text string >> Enter the Number : and then waits for input from the keyboard. The input can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix.It allows to write interactive programs.

12

You might also like