Learning about MATLAB

MATLAB which  stands for MATrix  LABoratory,  is a  software used for technical computing, algorithm development, modeling simulations and prototyping different systems.  MATLAB was initially developed to be a user-friendly front end to the popular FORTRAN  libraries LINPACK and EISPACK in the 1970s. Since that time, it has acquired an enormous user base in all fields of science and engineering by  effectively removing the need for scientists to master the intricacies of a general purpose programming language such as C or FORTRAN.

  MATLAB provides a suitable environment for discrete-time signal processing.  Since MATLAB  is optimized for vector operations, it is a natural choice for DSP simulations. There are many functions and libraries available in MATLAB  to analyze  signals and systems in  time and/or frequency domain. You will also write your own functions and scripts suited for specific design problems.

Getting Started

To start, run MATLAB on your PC workstation . You need to change the working directory to your default home directory before saving any of your scripts or functions.  Consult with your TA regarding your DSP account and the disk space.

 

On-Line help

There are several different ways to access online information about MATLAB functions.

 

Basic MATLAB

·        Scalar Arithmetic: 

MATLAB has all the standard scalar arithmetic operators for real and complex numbers:

Unless redefined by the user, 'i' and 'j' are special constants referring to the principal square toot of -1.

 

·        Variables

The MATLAB environment allows you to associate a name with a given numerical  quantity and then to refer to that quantity in later calculations by the name you have assigned. Note that variable names are case sensitive and can not be started with a number.

As shown above, 'pi' is a pre-defined variable. MATLAB stores all real variables as eight byte floating point numbers. The default display precision only reports the first digits after the decimal points. The display precision can be changed by using "format" command. You may read more about different expressions in MATLAB here.

·        Vector and Matrix Arithmetic

The fundamental data type in MATLAB  is a matrix. Note that vectors may be considered as matrices with only one row or column. There are several ways to create matrices in MATLAB; we will examine only a few of the simplest.

 A matrix can be manually constructed as shown below:

To turn a row vector into a column vector or vice-versa, or to transpose a matrix, the  transposition operator ( ' ) can be used. 

Note that in addition to being transposed, the single quote operator conjugated every element in the matrix. The conjugate transpose of a vector is sometimes called the  Hermitian of the vector. It is important not to get the the transpose operator (. ')  and the Hermitian operator ( ') confused. It would probably be wise  to always use (.') to transpose matrices unless you specifically require the conjugate.

The  arithmetic operations can be applied to matrices when the dimension of matrices are commensurate (as you know it from linear algebra).

There are also element-by-element operations defined for arrays with the same size. 

 

One very useful type of vector in signal processing is a vector whose elements form an arithmetic sequence. This type of vector is commonly used to create a matrix of times at which a signal (or function) is to be sampled. For example:

There are three special matrices that are often used in matrix operations. These matrices are zeros(m,n), ones(m,n) and eye(m,n):

 

To create a diagonal matrix with a given set of numbers on the diagonal, create a vector containing the numbers you want on the diagonal and then issue the  "diag" command.

MATLAB indexing of  a matrix starts with the number 1, rather than 0. In other words, the top left element in a matrix is element (1,1).   To refer to the element of a matrix in the (m;n)th  position, use the syntax A(m,n). You can use the colon operator ( :) to extract particular rows and/or  columns of a matrix. For example:

 

·        Functions

MATLAB provides a convenient  way to call an external function. the syntax for calling functions in MATLAB is very simple and similar to many other programming languages.  A function can be called from another function or script and  can return more than one variable. A general format of a function is as follows:

[var_1, var_2, ..., var_m]=function_name(arg_1,arg_2,...,arg_n)

The input and output arguments can be defined to be scalars,  vectors or matrices.  

There are many built-in functions provided by MATLAB. The built-in functions are  very efficient for vector  computation. Some examples of general purpose MATLAB functions are shown below. A more comprehensive list of  some useful functions and operators can be found in  the Reference

 

There are also several  libraries or Toolboxes of MATLAB functions written for specific applications. One particular Toolbox often used in this lab is Signal-Processing Toolbox.

 Often-Used Signal Processing Functions

 

Loops and Conditional Execution

MATLAB has two commands that may be used to create loops: for  and  while. To use a  for-loop, you must specify an index variable, a starting value for that variable, a n increment, and an ending value. MATLAB uses indexing vectors to perform all these tasks. 

In the loop above, the variable  k  is set to 1 on the first iteration and increases by 2 on each successive iteration. Loop execution stops when is greater than 20.

The while command may be used to create a loop that continues executing while some logical expression is true. The logical operators in MATLAB are similar to those in the C programming language. See the  Reference for a list of the logical operators. Run "help while" in MATLAB command line for more information and examples on how to use a while-loop. 

In addition to the loop constructs mentioned above, MATLAB also has several  statements for conditional execution of commands. These statements include if, else, elseif, switch and case.

 

Although it is probably important  to know about the  loop commands in MATLAB, it is equally important that you do not use them unless absolutely necessary! If you thoroughly understand the vector and matrix arithmetic, you should be able to avoid using  loops.

 

·        Creating Graphs

You can plot a one-dimensional signal in MATLAB using the plot command. For example, executing the next three lines in MATLAB command window will generate the following plot:

>> t=[-2*pi:0.05:2*pi];

>> x=cos(t);

>> plot(x)

There are a few changes we could do to make this plot more informative.First, the abscissa labels do not seem to match the input values. In fact, the axis seems to go from 0 to 300 by default, MATLAB labels the abscissa with the index of each sample. To specify the range of the x-axis, the plot command should be called with two arguments:

>> plot(t,x);

To specify the exact scaling and appearance of each axis in the current plot, the following command can be used:

>> axis([XMIN XMAX YMIN YMAX])

 The commands xlabel and ylabel are used to specify labels for the abscissa and ordinate, respectively. The command title is used to put a title on the current figure. You can  add grid to your plot by using grid command. For example:

Note that the line style, line types and many other properties of a plot  is configurable. Use help on plot for more details. There are several other commands to create different graphs:

·        subplot  places several plots in the same figure window.

·        semilogy: The same as PLOT(...), except a logarithmic (base 10) scale is used for the Y-axis.

 

Programming in MATLAB

·        Script M-files

A script file is an external file that contains a sequence of MATLAB statements. By typing the filename, subsequent MATLAB input is obtained from the file. Script files have a filename extension of .m and are often called M-files. Y ou can create a text file (usually called an M-file because of the standard .m extension in the file name) that contains a series of commands that will be executed in order. It is a good practice  that you always run scripts instead of typing commands directly  into the command window. 

 MATLAB provides a built in editor, although you can use any text editor you like. To open the editor , from the File menu in MATLAB window, choose New and then M-File. You can also simply double click on the existing M-file name to open it.

M-file scripts have access to all currently declared variables in the environment. Additionally, all variables that you declare inside the script are available in the command window once the script has finished executing. Note that by adding a semicolon (;) to the end of each line, you can  suppress the output being displayed. If you have a long calculation with many intermediate variables, you may want to put semicolons after each line but the line which computes the final result.  For example:

·        Function M-files

You add new functions to MATLAB's vocabulary by expressing them in terms of existing functions. The existing commands and functions that compose the new function reside in a text file called an M-file.

M-files can be either scripts or functions. Scripts are simply files containing a sequence of MATLAB statements. Functions make use of their own local variables and accept input arguments.

The name of an M-file begins with an alphabetic character, and has a filename extension of .m .   The M-file name, less its extension, is what MATLAB searches for when you try to use the script or function.

A line at the top of a function M-file contains the syntax definition. The name of a function, as defined in the first line of the M-file, should be the same as the name of the file without the .m extension. For example, the existence of a file on disk called stat.m with

 

function [mean,stdev] = stat(x)
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));

defines a new function called stat that calculates the mean and standard deviation of a vector. The variables within the body of the function are all local variables.

 

A subfunction, visible only to the other functions in the same file, is created by defining a new function with the function keyword after the body of the preceding function or subfunction. For example, avg is a subfunction within the file stat.m:

 

function [mean,stdev] = stat(x)
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);
 
function mean = avg(x,n)
mean = sum(x)/n;

Subfunctions are not visible outside the file where they are defined. Functions normally return when the end of the function is reached. Use a return statement to force an early return.

When MATLAB does not recognize a function by name, it searches for a file of the same name on disk. If the function is found, MATLAB compiles it into memory for subsequent use. 

For more information about how to create M-files read M-Files.

 

Exercises

Some MATLAB exercises can be found here . Please perform these exercises to enhance your Matlab knowledge.