MATLAB tutorial of fundamental programming

Document Sample
MATLAB tutorial of fundamental programming Powered By Docstoc
					  MATLAB® Tutorial of
Fundamental Programming




                     Prepared by:
         Khairul Anuar Ishak
Department of Electrical, Electronic & System Engineering
                 Faculty of Engineering
            Universiti Kebangsaan Malaysia
                                                 MATLAB tutorial of fundamental programming


Preface

    This tutorial introduces the fundamental ideas for programming in MATLAB. The objective
is to help you at solving the kinds of mathematical problems that you will likely encounter as an
engineering student, as well as a researcher. It requires no prior knowledge of MATLAB or
programming experience but if you have a strong background in mathematics and computer
programming then you can quickly learn how MATLAB can help you with your course work
and design projects. However, for those of you who are just starting out learning MATLAB, then
this tutorial is for you.


Remember, it is assumed throughout all chapters that you are following along, using MATLAB
and entering all commands shown. The questions and answers of the exercises, will be given
during the workshop went off.


On completion of the workshop, participants should be able to:
    •   Use MATLAB to solve certain mathematical problems.
    •   Produce a simple MATLAB program files (m-files).
    •   Use MATLAB effectively and also being ready to explore more of MATLAB on your
        own.


Enjoy the MATLAB! ;-)


Notes: You can e-mail me if you have any problems or corrections about these pieces of code, or
if you would like to add your own tips to those described in this document.


Khairul Anuar Ishak
e-mail: nuarscc@yahoo.com




                                                                                                i
                                     MATLAB tutorial of fundamental programming




                                 Contents

1   Introduction to MATLAB                                                     1
    What is MATLAB?                                                            1
    MATLAB System                                                              2
    The Advantages of MATLAB                                                   2
    Disadvantages of MATLAB                                                    3
2   Getting Started                                                            4
    Starting MATLAB                                                            4
    Ending a Session                                                           8
3   MATLAB Basics                                                              9
    Variables and Arrays                                                       9
    Arithmetic Operations                                                     14
    Common MATLAB Functions                                                   16
4   Plotting and Visualization                                                17
    Plotting in MATLAB                                                        17
    Images in MATLAB                                                          24
5   Programming                                                          25
    Data Types                                                                25
    M-File Programming                                                        27
    Flow Control                                                         30




                                                                               ii
CHAPTER 1: Introduction to MATLAB
                                                                            What is MATLAB?

                                     CHAPTER 1
                         Introduction to MATLAB


What is MATLAB?

    MATLAB (short for MATrix LABoratory) is a special-purpose computer program optimized
to perform engineering and scientific calculations. It is a high-performance language for
technical computing. It integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar mathematical notation.
Typical uses include:

           Math and computation
           Algorithm development
           Modelling, simulation and prototyping
           Data analysis, exploration and visualization
           Scientific and engineering graphics
           Application development, including Graphical User Interface (GUI) building


    MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar non-interactive language such as C, C++ or Fortran.

   MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering and science. In industry, MATLAB is the tool of choice for high-
productivity research, development and analysis.

    MATLAB features a family of application-specific solution called Toolboxes. Very
important to most users of MATLAB, toolboxes allow you to learn and apply specialized
technology. Toolboxes are comprehensive collections of MATLAB function (m-files) that
extend the MATLAB environment to solve particular classes of problems. Areas in which
toolboxes are available include signal processing, control systems, neural networks, fuzzy logic,
wavelets, image processing, simulation and many others.




                                                                                                1
CHAPTER 1: Introduction to MATLAB
                                                                            MATLAB System

MATLAB System

The MATLAB system consists of five main parts:

   1. The MATLAB language. This is a high-level matrix/array language with control flow
      statements, functions, data structures, input/output, and object-oriented programming
      features. It allows both “programming in the small” to rapidly create quick and dirty
      throw-away programs, and “programming in the large” to create complete large and
      complex application programs.
   2. The MATLAB working environment. This is the set of tools and facilities that you
      work with as the MATLAB user or programmer. It includes facilities for managing the
      variables in your workspace and importing and exporting data. It also includes tools for
      developing, managing, debugging, and profiling M-files, MATLAB’s applications.
   3. Handle Graphics. This is the MATLAB graphics system. It includes high-level
      commands for two-dimensional and three-dimensional data visualization, image
      processing, animation, and presentation graphics. It also includes low-level commands
      that allow you to fully customize the appearance of graphics as well as to build complete
      Graphical User Interfaces on your MATLAB applications.
   4. The MATLAB mathematical function library. This is a vast collection of
      computational algorithms ranging from elementary functions like sum, sine, cosine, and
      complex arithmetic, to more sophisticated functions like matrix inverse, matrix
      eigenvalues, Bessel functions, and fast Fourier transforms.
   5. The MATLAB Application Program Interface (API). This is a library that allows you
      to write C and Fortran programs that interact with MATLAB. It include facilities for
      calling routines from MATLAB (dynamic linking), calling MATLAB as a computational
      engine, and for reading and writing MAT-files.



The Advantages of MATLAB

   MATLAB has many advantages compared to conventional computer languages for technical
problem solving. Among them are:

   1. Ease of Use. MATLAB is an interpreted language. Program may be easily written and
      modified with the built-in integrated development environment and debugged with the
      MATLAB debugger. Because the language is so easy to use, it is ideal for the rapid
      prototyping of new programs.
   2. Platform Independence. MATLAB is supported on many different computer systems,
      providing a large measure of platform independence. At the time of this writing, the
      language is supported on Windows NT/2000/XP, Linux, several versions of UNIX and
      the Macintosh.
   3. Predefined Function. MATLAB comes complete with an extensive library of predefined
      functions that provide tested and pre-packaged solutions to many basic technical tasks.
      For examples, the arithmetic mean, standard deviation, median, etc. these and hundreds
      of other functions are built right into the MATLAB language, making your job much
      easier. In addition to the large library of function built into the basic MATLAB language,

                                                                                              2
CHAPTER 1: Introduction to MATLAB
                                                                  Disadvantages of MATLAB

      there are many special-purpose toolboxes available to help solve complex problems in
      specific areas. There is also an extensive collection of free user-contributed MATLAB
      programs that are shared through the MATLAB Web site.
   4. Device-Independent Plotting. Unlike most other computer languages, MATLAB has
      many integral plotting and imaging commands. The plots and images can be displayed on
      any graphical output device supported by the computer on which MATLAB is running.
   5. Graphical User Interface. MATLAB includes tools that allow a programmer to
      interactively construct a graphical user interface, (GUI) for his or her program. With this
      capability, the programmer can design sophisticated data-analysis programs that can be
      operated by relatively inexperienced users.
   6. MATLAB Compiler. MATLAB’s flexibility and platform independence is achieved by
      compiling MATLAB programs into a device-independent p-code, and then interpreting
      the p-code instructions at runtime. Unfortunately, the resulting programs can sometimes
      execute slowly because the MATLAB code is interpreted rather than compiled.



Disadvantages of MATLAB

    MATLAB has two principal disadvantages. The first is that it is an interpreted language and
therefore can execute more slowly than compiled languages. This problem can be mitigated by
properly structuring the MATLAB program, and by the use of the MATLAB compiler to
compile the final MATLAB program before distribution and general use.

    The second disadvantage is cost: a full copy of MATLAB is five to ten times more expensive
than a conventional C or Fortran compiler. This relatively high cost is more than offset by then
reduced time required for an engineer or scientist to create a working program, so MATLAB is
cost-effective for businesses. However, it is too expensive for most individuals to consider
purchasing. Fortunately, there is also an inexpensive Student Edition of MATLAB, which is a
great tool for students wishing to learn the language. The Student Edition of MATLAB is
essentially identical to the full edition.




                                                                                               3
CHAPTER 2: Getting Started
                                                                             Starting MATLAB

                                     CHAPTER 2
                                   Getting Started


Starting MATLAB

   You can start MATLAB by double-clicking on the MATLAB icon or invoking the
application from the Start menu of Windows. The main MATLAB window, called the
MATLAB Desktop, will then pop-up and it will look like this:




                          Figure 2.1: The Default MATLAB desktop

    When MATLAB executes, it can display several types of windows that accept commands or
display information. It integrates many tools for managing files, variables and applications within
the MATLAB environment. The major tools within or accessible from the MATLAB desktop
are:

   1.   The Current Directory Browser
   2.   The Workspace Window
   3.   The Command Window
   4.   The Command History Window
   5.   The Start Button
   6.   The Help Window

                                                                                                 4
CHAPTER 2: Getting Started
                                                                          Starting MATLAB

   If desired, this arrangement can be modified by selecting an alternate choice from [View]
[Desktop Layout]. By default, most MATLAB tools are “docked” to the desktop, so that they
appear inside the desktop window. However, you can choose to “undock” any or all tools,
making them appear in windows separate from the desktop.

The Command Window




                             Figure 2.2: The Command Window

    The Command Window is where the command line prompt for interactive commands is
located. Once started, you will notice that inside the MATLAB command window is the text:


  To get started, select “MATLAB Help” from the Help menu.

  >>


    Click in the command window to make it active. When a window becomes active, its titlebar
darkens. The “>>” is called the Command Prompt, and there will be a blinking cursor right after
it waiting for you to type something. You can enter interactive commands at the command
prompt (>>) and they will be executed on the spot.

    As an example, let’s enter a simple MATLAB command, which is the date command. Click
the mouse where the blinking cursor is and then type date and press the ENTER key. MATLAB
should then return something like this:

 >> date

 ans =

 01-Sep-2006



   Where the current date should be returned to you instead of 01-Sep-2006. Congratulation!
You have just successfully executed your first MATLAB command!




                                                                                             5
CHAPTER 2: Getting Started
                                                                             Starting MATLAB

The Command History Window




                          Figure 2.3: The Command History Window

    The Command History Window, contains a log of commands that have been executed within
the command window. This is a convenient feature for tracking when developing or debugging
programs or to confirm that commands were executed in a particular sequence during a multi-
step calculation from the command line.

The Current Directory Browser




                              Figure 2.4: The Directory Browser

    The Current Directory Browser displays a current directory with a listing of its contents.
There is navigation capability for resetting the current directory to any directory among those set
in the path. This window is useful for finding the location of particular files and scripts so that
they can be edited, moved, renamed or deleted. The default directory is the Work subdirectory of
the original MATLAB installation directory.




                                                                                                 6
CHAPTER 2: Getting Started
                                                                                Starting MATLAB

The Workspace Window




                               Figure 2.5: The Workspace Window

    The Workspace Window provides an inventory of all the items in the workspace that are
currently defined, either by assignment or calculation in the Command Window or by importing
with a load or similar command from the MATLAB command line prompt. These items consist
of the set of arrays whose elements are variables or constants and which have been constructed or
loaded during the current MATLAB session and have remained stored in memory. Those which
have been cleared and no longer are in memory will not be included. The Workspace Window
shows the name of each variable, its value, its array size, its size in bytes, and the class. Values of
a variable or constant can be edited in an Array Editor which is launched by double clicking its
icon in the Workspace Window.

The Help Window




                                  Figure 2.6: The Help Window



                                                                                                     7
CHAPTER 2: Getting Started
                                                                                   Ending a Session

    You can access the online help in one of several ways. Typing help at the command prompt
will reveal a long list of topics on which help is available. Just to illustrate, try typing help
general. Now you see a long list of “general purpose” MATLAB commands. In addition, you
can also get help on the certain command. For example, date command. The output of help also
refers to other functions that are related. In this example the help also tells you, See also NOW,
CLOCK, DATENUM. You can now get help on these functions using the three different commands
as well.

 >> help date

  DATE   Current date as date string.
     S = DATE returns a string containing the date in dd-mmm-yyyy format.

      See also NOW, CLOCK, DATENUM.



     There is a much more user-friendly way to access the online help, namely via the MATLAB
Help Browser. Separate from the main desktop layout is a Help desktop with its own layout. This
utility can be launched by selecting [Help] [MATLAB Help] from the Help pull down menu.
This Help desktop has a right side which contains links to help with functions, help with
graphics, and tutorial type documentation.

The Start Button
    The Start Button (see figure 2.1) allows a user to access MATLAB tools, desktop tools, help
files, etc. it works just like the Start button on a Windows desktop. To start a particular tool, just
click on the Start Button and select the tool from the appropriate sub-menu.

Interrupting Calculations
    If MATLAB is hung up in a calculation, or is just taking too long to perform an operation,
you can usually abort it by typing [CTRL + C] (that is, hold down the key labeled CTRL, and press
C).


Ending a Session
    One final note, when you are all done with your MATLAB session you need to exit
MATLAB. To exit MATLAB, simply type quit or exit at the prompt. You can also click on the
special symbol that closes your windows (usually an × in the upper right-hand corner). Another
way to exit is by selecting [File] [Exit MATLAB]. Before you exit MATLAB, you should be
sure to save any variables, print any graphics or other files you need, and in general clean up
after yourself.




                                                                                                    8
CHAPTER 3: MATLAB Basics
                                                                          Variables and Arrays

                                    CHAPTER 3
                                 MATLAB Basics


Variables and Arrays

    The fundamental unit of data in any MATLAB program is the array. An array is a collection
of data values organized into rows and columns and known by a single name. Individual data
values within an array are accessed by including the name of the array followed by subscripts in
parentheses that identify the row and column of the particular value. Even scalars are treated as
arrays by MATLAB – they are simply arrays with only one row and one column. There are three
fundamental concepts in MATLAB, and in linear algebra, are scalars, vectors and matrices.

   1. A scalar is simply just a fancy word for a number (a single value).
   2. A vector is an ordered list of numbers (one-dimensional). In MATLAB they can be
      represented as a row-vector or a column-vector.
   3. A matrix is a rectangular array of numbers (multi-dimensional). In MATLAB, a two-
      dimensional matrix is defined by its number of rows and columns.


                            This is a scalar, containing 1 element
    a = 10

    b = [1 2 3 4]           This is a 1×4 array containing 4 elements, known as a row vector


        ⎡1⎤
                           This is a 3×1 array containing 3 elements, known as a column vector
    c = ⎢2⎥
        ⎢ ⎥
        ⎢3⎥
        ⎣ ⎦

        ⎡1 2 3⎤             This is a 3×3 matrix, containing 9 elements
    d = ⎢4 5 6⎥
        ⎢     ⎥
        ⎢7 8 9⎥
        ⎣     ⎦
   In MATLAB matricies are defined inside a pair of square braces ([]). Punctuation marks of a
comma (,), and semicolon (;) are used as a row separator and column separator, respectfully.
You can also use a space as a row separator, and a carriage return (the ENTER key) as a column
separator as well.



                                                                                               9
CHAPTER 3: MATLAB Basics
                                                                           Variables and Arrays

Examples 3.1

Below are examples of how a scalar, vector and matrix can be created in MATLAB.
  >> my_scalar = 3.1415

  my_scalar =
                                                  >> my_vector1 = [1 5 7]
  3.1415
                                                  my_vector1 =
  >> my_vector1 = [1, 5, 7]
                                                  1         5    7
  my_vector1 =

  1      5      7
                                                  >> my_vector2 = [1
                                                                   5
  >> my_vector2 = [1; 5; 7]                                        7]
  my_vector2 =                                    my_vector2 =
  1                                               1
  5                                               5
  7                                               7


  >> my_matrix = [8 12 19; 7 3 2; 12 4 23; 8 1 1]

  my_matrix =

  8 12 19
  7 3 2
  12 4 23
  8 1 1


Indexing into an Array
Once a vector or a matrix is created you might needed to extract only a subset of the data, and
this is done through indexing.

                           Row 1                                A 2-by-3
                                                                 Matrix
                           Row 2

                                        Col 1 Col 2 Col 3

      Figure 3.1: An array is a collection of data values organized into rows and columns




                                                                                             10
CHAPTER 3: MATLAB Basics
                                                                           Variables and Arrays
     Individual elements in an array are addressed by the array name followed by the row and
column of the particular element. If the array is a row or column vector, then only one subscript
is required. For example, according to the example 3.1:

       o my_vector2(2) is 5
       o my_matrix(3,2) is 4 or my_matrix(7) is 4

The Colon Operator
   The colon (:) is one of MATLAB’s most important operators. It occurs in several different
forms.

Examples 3.2

   1. To create an incremental or a decrement vector
  >> my_inc_vec1 = [1:7]           >> my_inc_vec2 = [1:2:7]             >> my_dec_vec = [5:-2:1]

  my_inc_vec1 =                    my_inc_vec2 =                        my_dec_vec =

  [ 1 2 3 4 5 6 7]                 [ 1 3 5 7]                           [ 5 3 1]



   2. To refer portions of a matrix/vector
   >> my_matrix = [8 12 19; 7 3 2; 12 4 23; 8 1 1]

   my_matrix =

    8 12 19
    7 3 2
   12 4 23
    8 1 1

   >> new_matrix1 = my_matrix(1:3,2:3)

   new_matrix1 =

   12 19
    3 2
    4 23

   >> new_matrix2 = my_matrix(2:4,:)

   new_matrix2 =

   12 4 23
    8 1 1



∗ NOTES: If the colon is used by itself within subscript, it refers to all the elements in a row or
column of a matrix!


                                                                                                11
CHAPTER 3: MATLAB Basics
                                                                        Variables and Arrays

Concatenating Matrices
   Matrix concatenation is the process of joining one or more matrices to make a new matrix.
The expression C = [A B] horizontally concatenates matrices A and B. The expression C = [A;
B] vertically concatenates them.

Examples 3.3
 >> A = [8 19; 7 2];
 >> B = [1 64; 4 5; 3 78];
 >> C = [A; B]

 C =

  8     19
  7      2
  1     64
  4      5
  3     78



Reshaping a Matrix
   Here are a few examples to illustrate some of the ways you can reshape matrices.

Examples 3.4

Reshape 3-by-4 matrix A to have dimensions 2-by-6.

 >> A = [1 4 7 10; 2 5 8 11; 3 6 9 12]

 A =

   1      4       7     10
   2      5       8     11
   3      6       9     12

 >> B = reshape(A, 2, 6)

 B =

   1      3       5      7      9     11
   2      4       6      8     10     12




                                                                                          12
CHAPTER 3: MATLAB Basics
                                                                            Variables and Arrays

Examples 3.5

Transpose A so that the row elements become columns or vice versa. You can use either the
transpose function or the transpose operator (’). To do this:

 >> A = [1 4 7 10; 2 5 8 11; 3 6 9 12];
 >> B = A’

 B =

   1       2      3
   4       5      6
   7       8      9
  10      11     12


General Function for Matrix and Vector
    There are many MATLAB features which cannot be included in these introductory notes.
Listed below are some of the MATLAB functions regard to matrix and vector.

Basic Vector Function

   MATLAB includes a number of built-in functions that you can use to determine a number of
characteristics of a vector. The following are the most commonly used such functions.

size                  Returns the dimensions of a matrix
length                Returns the number of elements in a matrix
min                   Returns the minimum value contained in a matrix
max                   Returns the maximum value contained in a matrix
sum                   Returns the sum of the elements in a matrix
sort                  Returns the sorted elements in a matrix
abs                   Returns the absolute value of the elements in a matrix

Examples 3.6

The following example demonstrates the use some of these functions.

 >> A = [3 1 2 4];                  >> mnA = min(A)              >> sumA = sum(A)
 >> szA = size(A)
                                    mnA =                        sumA =
 szA =
                                      1                            10
   1       4                        >> mxA = max(A)
                                                                 >> stA = sort(A)
 >> lenA = length(A)                mxA =
                                                                 stA =
 lenA =                                4
                                                                   1    2    3   4
   4




                                                                                              13
CHAPTER 3: MATLAB Basics
                                                                      Arithmetic Operations

Functions to Create a Matrix

This following section summarizes the principal functions used in creating and handling
matrices. Most of these functions work on multi-dimensional arrays as well.

diag                 Create a diagonal matrix from a vector
cat                  Concatenate matrices along the specified dimension
ones                 Create a matrix of all ones
zeros                Create a matrix of all zeros
rand                 Create a matrix of uniformly distributed random numbers
repmat               Create a new matrix by replicating or tiling another

Examples 3.7

The following example demonstrates the use some of these functions.

 >> A = zeros(2,4)                  >> C = rand(4,3)

 A =                                C =

   0     0   0   0                        0.9501    0.8913      0.8214
   0     0   0   0                        0.2311    0.7621      0.4447
                                          0.6068    0.4565      0.6154
 >> B = 7*ones(1,3)                       0.4860    0.0185      0.7919

 B =

   7     7   7




Arithmetic Operations
    MATLAB can be used to evaluate simple and complex mathematical expressions. When we
move from scalars to vectors (and matrices), some confusion arises when performing arithmetic
operations because we can perform some operations either on an element-by-element (array
operation) or matrices as whole entities (matrix operation). Expressions use familiar
arithmetic operators:

Array Operators
Operation            MATLAB Form           Comments
Addition                 A + B             Array addition is identical
Subtraction              A - B             Array subtraction is identical
Multiplication           A .* B            Element-by-element multiplication of A and B. Both
                                           arrays must be the same shape, or one of them must
                                           be a scalar
Division                 A ./ B            Element-by-element division of A and B. Both arrays
                                           must be the same shape, or one of them must be a
                                           scalar

                                                                                           14
CHAPTER 3: MATLAB Basics
                                                                       Arithmetic Operations

Power                     A .^ B          Element-by-element exponentiation of A and B. Both
                                          arrays must be the same shape, or one of them must
                                          be a scalar

Examples 3.8

The following example demonstrates the use some of these operations.

 >> A = [1 4 7 10; 2 5 8 11; 3 6 9 12]                 >> A = [1 2 3 4];
                                                       >> B = A.^2
 A =                                                   B =

        1        4   7      10                                1    4      9     16
        2        5   8      11
        3        6   9      12
                                                       >> A = [ 2 4 ; 8 10]
 >> B = [1 2 3 4; 5 6 7 8; 9 10 11 12]                 A =

 B =                                                          2    4
                                                              8   10
        1     2       3      4
        5     6       7      8                         >> B = [2 4; 2 5]
        9    10      11     12                         B =

 >> C = A.*B                                                  2    4
                                                              2    5
 C =
                                                       >> C = A./B
         1    8      21     40                         C =
        10   30      56     88
        27   60      99    144                                1    1
                                                              4    2


Matrix Operators
Operation            MATLAB Form          Comments
Addition                  A + B           Array addition is identical
Subtraction               A - B           Array subtraction is identical
Multiplication            A * B           Matrix multiplication of A and B. The number of
                                          columns in A must equal the number of rows in B.
Division                  A / B           Matrix division defined by A * inv(B), where
                                          inv(B) is the inverse of matrix B.
Power                     A ^ B           Matrix exponentiation of A and B. The power is
                                          computed by repeated squaring

Examples 3.9
 >> A = [ 2 4 ; 8 10];                       >> A = [ 2 4 ; 8 10];
 >> B = [2 4; 2 5];                          >> B = [2 4; 2 5];
 >> C = A*B                                  >> C = B*A
 C =                                         C =

        12   28                                   36     48
        36   82                                   44     58

                                                                                          15
CHAPTER 3: MATLAB Basics
                                                                   Common MATLAB Functions

Built-in Variables
    MATLAB uses a small number of names for built-in variables. An example is the ans
variable, which is automatically created whenever a mathematical expression is not assigned to
another variable. Table below lists the built-in variables and their meanings. Although you can
reassign the values of these built-in variables, it is not a good idea to do so, because they are used
by the built-in functions.

Variable                                             Meaning
    ans       Value of an expression when that expression is not assigned to a variable
    eps       Floating-point precision
              Unit imaginary number, i = j = −1
    i,j
    pi        π , 3.14159265 …
 realmax      Largest positive floating-point number
 realmin      Smallest positive floating-point number
   Inf                                                                   1
              ∞ , a number larger than realmax, the result of evaluating
                                                                         0
    NaN                                                     0
              Not a number, (e.g., the result of evaluating
                                                            0

Examples 3.10
 >> x = 0;                                       >> x = 0;
 >> 5/x                                          >> x/x

 Warning: Divide by zero                         Warning: Divide by zero
 ans =                                           ans =
        Inf                                             NaN




Common MATLAB Functions
   A few of the most common and useful MATLAB functions are shown in table below. These
functions will be used in many times. It really helps you when one needs to manage variables and
workspace and to perform an elementary mathematical operation.

Managing Variables and Workspace
                       who       List current variables
                      whos       List current variables, long form
                     clear       Clear variables and functions from memory
                      disp       Display matrix or text
                       clc       Clear command window
                      demo       Run demonstrations




                                                                                                   16
CHAPTER 3: MATLAB Basics
                                                               Common MATLAB Functions

Examples 3.11
 >> whos                                     >> str = [‘MATLAB Baguss..!’];
 Name Size      Bytes   Class                >> disp(str);
 ans    1x1     226     sym object
 y      1x1       8     char array           MATLAB Baguss..!
 v      4x5     200     double array
 x      1x3     500     double array




Built-in Function of Elementary Math
 abs(x)     Calculates x
angle(x)    Returns the phase angle of the complex value x, in radians
 exp(x)     Calculates ex
 mod(x)     Remainder or modulo function
 log(x)     Calculates the natural logarithm loge x
 sqrt(x)    Calculates the square root of x
  sin(x)    Calculates the sin(x), with x in radians
  cos(x)    Calculates the cos(x), with x in radians
  tan(x)    Calculates the tan(x), with x in radians
 ceil(x)    Rounds x to the nearest integer towards positive infinity
  fix(x)    Rounds x to the nearest integer towards zero
floor(x)    Rounds x to the nearest integer towards minus infinity
round(x)    Rounds x to the nearest integer

Examples 3.12
 >> z = 2*sin(pi/2)+log(2)                 >> z = 2*sin(pi/2)+log(2)

 z =                                       z =

       2.6931                                    2.6931

 >> z = round(z)                           >> z = round(z)

 z =                                       z =

       3                                         3




                                                                                    17
CHAPTER 4: Plotting and Visualization
                                                                            Plotting in MATLAB

                                     CHAPTER 4
                          Plotting and Visualization


Plotting in MATLAB

   MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. This section describes a few of the most important graphics
functions and provides examples of some typical applications.

Creating a Plot
    The plot function has different forms, depending on the input arguments. If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements
of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.

For example, to plot the value of the sine function from zero to 2π, use:

Creating Line Plots

Examples 4.1




 >> x = 0:pi/100:2*pi;
 >> y = sin(x);
 >> plot(x,y);




                                                                                              18
CHAPTER 4: Plotting and Visualization
                                                                         Plotting in MATLAB

    This is the basic command of plotting a graph. Besides that, MATLAB has commands which
will let you add titles and labels and others in order to make your figures more readable.
However, you need to keep the figure window open while executing these commands.




 >>   xlabel(‘Radian’);
 >>   ylabel(‘Amplitude’);
 >>   title(‘Plot of sin(x) vs x’);
 >>   grid on;




  The current limits of this plot can be determined from the basic axis function. So, in order to
modify the x-axis within [0 2π], you need to run this function:




 >> axis([0 2*pi -1 1]);




                                                                                              19
CHAPTER 4: Plotting and Visualization
                                                                       Plotting in MATLAB

Annotating Plots

   You can adjust the axis tick-mark locations and the labels appearing at each tick mark. For
example, this plot of the sine function relabels the x-axis with more meaningful values.

Example 4.2

 >>   x = 0:pi/100:2*pi;
 >>   y = sin(x);
 >>   plot(x,y);
 >>   set(gca,’XTick’,-pi:pi/2:pi);
 >>   set(gca,’XTickLabel’,{‘-pi’,’-pi/2’,’0’,’pi/2’,’pi’});
 >>   xlabel('-\pi \leq \Theta \leq \pi');
 >>   ylabel('sin(\Theta)');
 >>   title('Plot of sin(\Theta)');




Creating a Semilogarithmic Plot

   Semilogarithmic plot is another type of figuring a graph by rescaling if the new data falls
outside the range of the previous axis limits.

Example 4.3



 >>   x = linspace(0,3);
 >>   y = 10*exp(-2*x);
 >>   semilogy(x,y);
 >>   grid on;




                                                                                           20
CHAPTER 4: Plotting and Visualization
                                                                            Plotting in MATLAB

Specifying the Color and Size of Lines

You can control a number of line style characteristics by specifying values for line properties.

LineWidth            Width of the line in units of points
MarkerEdgeColor      Color of the marker or the edge color for filled markers
MarkerFaceColor      Color of the face of filled markers
MarkerSize           Size of the marker in units of points


Example 4.4
 >> x = -pi:pi/10:pi;
 >> y = tan(sin(x)) - sin(tan(x));
 >> plot(x,y,'--rs','LineWidth',2,...
    'MarkerEdgeColor','k',...
    'MarkerFaceColor','g','MarkerSize',10);




Multiple Plots
    Often, it is desirable to place more than one plot in a single figure window. This is achieved
by three ways:

The subplot Function

    The subplot Function breaks the figure window into an m-by-n matrix of small subplots and
selects the ith subplot for the current plot. The plots are numbered along the top row of the figure
window, then the second row, and so forth.




                                                                                                   21
CHAPTER 4: Plotting and Visualization
                                                                            Plotting in MATLAB

Example 4.5


 >>   x = linspace(0,2*pi);
 >>   subplot(2,2,1);
 >>   plot(x,sin(x));
 >>
 >>   subplot(2,2,2)
 >>   plot(x,sin(2*x));
 >>
 >>   subplot(2,2,3)
 >>   plot(x,sin(3*x));
 >>
 >>   subplot(2,2,4)
 >>   plot(x,sin(4*x));



Multiple plots

    You can assign different line styles to each data set by passing line style identifier strings to
plot and placing a legend on the plot to identify curves drawn with different symbol and line
types.

Example 4.6

 >>   x = linspace(0,2*pi);
 >>   y1 = sin(x);
 >>   y1 = cos(x);
 >>   y1 = tan(x);
 >>   plot(x,y1,x);
 >>   axis([0 2*pi -1 1]);




The hold Function

The hold command will add new plots on top of previously existing plots.

Example 4.6

 >>   x = -pi:pi/20:pi;
 >>   y1 = sin(x);
 >>   y2 = cos(x);
 >>   plot(x,y1,'b-');
 >>   hold on;
 >>   plot(x,y2,'g--');
 >>   hold off;
 >>   legend('sin(x)','cos(x)');




                                                                                                  22
CHAPTER 4: Plotting and Visualization
                                                                          Plotting in MATLAB

Line Plots in Three-Dimensions
    Now, the three-dimension analog of the plot function is plot3. if x, y and z are three vectors
of the same length, plot3(x,y,z) generates a line in 3-D through the points whose coordinates
are the elements of x, y and z and then produces a 2-D projection of that line on the screen.

Example 4.7

 >>   Z = [0 : pi/50 : 10*pi];
 >>   X = exp(-.2.*Z).*cos(Z);
 >>   Y = exp(-.2.*Z).*sin(Z);
 >>   plot3(X,Y,Z,'LineWidth',2);
 >>   grid on;
 >>   xlabel('x-axis');
 >>   ylabel('y-axis');
 >>   zlabel('z-axis');




Three-Dimensional Surface Mesh Plots
   The first step in displaying a function of two variables, z = f(x,y), is to generate X and Y
matrices consisting of repeated rows and columns, respectively, over the domain of the function.
Then use these matrices to evaluate and graph the function. Meshgrid function transforms the
domain specified by two-vectors, x and y, into matrices X and Y.

Example 4.8

 >>   [X,Y] = meshgrid(-8:.5:8);
 >>   R = sqrt(X.^2 + Y.^2);
 >>   Z = sin(R)./R;
 >>   mesh(X,Y,Z);




                                                                                               23
CHAPTER 4: Plotting and Visualization
                                                                             Images in MATLAB

Images in MATLAB

    The basic data structure in MATLAB is the array, an ordered set of real or complex
elements. Thus, MATLAB stores most images as two-dimensional arrays (i.e., matrices), in
which each element of the matrix corresponds to a single pixel in the displayed image. For
example, an image composed of 200 rows and 300 columns or different colored dots would be
stored in MATLAB as a 200-by-300 matrix. Some images, such as RGB, require a three-
dimensional array, where the first plane in the third dimension represents the red pixel intensities,
the second plane represents the green pixel intensities, and the third plane represents the blue
pixel intensities.

This example reads an 8-bit RGB image into MATLAB and converts it to a grayscale image.

Example 4.9

 >>   rgb_img = imread('ngc6543a.jpg');
 >>   image(rgb_img);
 >>   pause;
 >>   graysc_img = rgb2gray(rgb_img);
 >>   imshow(graysc_img);




                                                                                                  24
CHAPTER 5: Programming
                                                                                       Data Types

                                     CHAPTER 5
                                     Programming


Data Types

    There are many different types of data that you can work with in MATLAB. You can build
matrices and arrays of floating point and integer data, characters and strings, logical true and
false states, etc. you can also develop your own data types using MATLAB classes. Two of the
MATLAB data types, structures and cell arrays, provide a way to store dissimilar types of data in
the same array.

    There are 15 fundamental data types (or classes) in MATLAB. Each of these data types is in
the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional
array of any size. Two-dimensional versions of these arrays are called matrices. All of the
fundamental data types are shown in lowercase text in the diagram below. Additional data types
are user-defined, object-oriented user classes (a subclass of structure), and java classes, that you
can use with the MATLAB interface to Java. Matrices of type double and logical may be either
full or sparse. For matrices having a small number of nonzero elements, a sparse matrix requires
a fraction of the storage space required for an equivalent full matrix. Sparse matrices invoke
special methods especially tailored to solve sparse problems.


                                             ARRAY
                                         (full or sparse)




logical         char      NUMERIC       CELL        structure         Java         Function
                                                                     Classes        handle




     int8, unit8,
                           single              double
    int16, uint16,
    int32, uint32,
    int64, uint64




                                                                                                 25
CHAPTER 5: Programming


The following table describes these data types in more detail.

Data type           Example             Description
 int8, unit8,            int16(100)     Signed and unsigned integer arrays that are 8, 16,
int16, uint16,
                                        32, and 64 bits in length. Enables you to manipulate
int32, uint32,
int64, uint64                           integer quantities in a memory efficient manner.
                                        These data types cannot be used in mathematical
                                        operations.
char                'Hello'             Character array (each character is 16 bits long). This
                                        array is also referred to as a string.
logical             magic(4) > 10       Logical array. Must contain only logical 1 (true) and
                                        logical 0 (false) elements. (Any nonzero values
                                        converted to logical become logical 1.) Logical
                                        matrices (2-D only) may be sparse.
single              3*10^38             Single-precision numeric array. Single precision
                                        requires less storage than double precision, but has
                                        less precision and a smaller range. This data type
                                        cannot be used in mathematical operations.
double              3*10^300            Double-precision numeric array. This is the most
                    5+6i
                                        common MATLAB variable type. Double matrices
                                        (2-D only) may be sparse.
cell                {17         'hello' Cell array. Elements of cell arrays contain other
                    eye(2)}             arrays. Cell arrays collect related data and
                                        information of a dissimilar size together.
structure           a.day = 12;         Structure array. Structure arrays have field names.
                    a.color = 'Red';    The fields contain other arrays. Like cell arrays,
                    a.mat = magic(3);
                                        structures collect related data and information
                                        together.
function            @humps              Handle to a MATLAB function. A function handle
handle                                  can be passed in an argument list and evaluated
                                        using feval
user class          inline('sin(x)')    MATLAB class. This user-defined class is created
                                        using MATLAB functions.
java class          java.awt.Frame      Java class. You can use classes already defined in
                                        the Java API or by a third party, or create your own
                                        classes in the Java language.




                                                                                           26
CHAPTER 5: Programming



M-File Programming

    MATLAB provides a full programming language that enables you to write a series of
MATLAB statements into a file and then execute them with a single command. You write your
program in an ordinary text file, giving the file a name of filename.m. The term you use for
filename becomes the new command that MATLAB associates with the program. The file
extension of .m makes this a MATLAB M-file. M-files can be scripts that simply execute a series
of MATLAB statements, or they can be functions that also accept arguments and produce output.
You create M-files using a text editor, then use them as you would any other MATLAB function
or command. The process looks like this:




Kinds of M-files
There are two kinds of M-files

Script M-files                              Function M-files
                                            Can accept input arguments and return output
Do not accept input arguments or return output
arguments                                   arguments
Operate on data in the workspace            Internal variables are local to the function by
                                            default
Useful for automating a series of steps you Useful for extending the MATLAB language
need to perform many times                  for you application




                                                                                            27
CHAPTER 5: Programming


Scripts
   Scripts are the simplest kind of M-file because they have no input or output arguments.
They're useful for automating series of MATLAB commands, such as computations that you
have to perform repeatedly from the command line. Scripts operate on existing data in the
workspace, or they can create new data on which to operate. Any variables that scripts create
remain in the workspace after the script finishes so you can use them for further computations.

Example 5.1


   % An M-file script to produce               % Comment lines
   % "flower petal" plots
   theta = -pi:0.01:pi;                        % Computations
   rho(1,:) = 2*sin(5*theta).^2;
   rho(2,:) = cos(10*theta).^3;
   rho(3,:) = sin(theta).^2;
   for k = 1:3
       polar(theta,rho(k,:))                   % Graphics output
       pause
   end




    Try entering these commands in an M-file called petals.m. This file is now a MATLAB
script. Typing petals at the MATLAB command line executes the statements in the script.




                                                                                            28
CHAPTER 5: Programming


Functions
   Functions are M-files that accept input arguments and return output arguments. They operate
on variables within their own workspace. This is separate from the workspace you access at the
MATLAB command prompt.

Example 5.2


   function y = average(x)
   % AVERAGE Mean of vector elements.
   % AVERAGE(X), where X is a vector, is the mean of vector elements.
   % Nonvector input results in an error.

   [m,n] = size(x);
   if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
       error('Input must be a vector')
   end

   y = sum(x)/length(x);            % Actual computation




   If you would like, try entering these commands in an M-file called average.m. The average
function accepts a single input argument and returns a single output argument. To call the
average function, enter



 >> z = 1:99;
 >> average(z)

 ans =
     50




The Function Definition Line

   The function definition line informs MATLAB that the M-file contains a function, and
specifies the argument calling sequence of the function. The function definition line for the
average function is




                                                                                           29
CHAPTER 5: Programming


All MATLAB functions have a function definition line that follows this pattern.

    The Function Name - MATLAB function names have the same constraints as variable
names. The name must begin with a letter, which may be followed by any combination of letters,
digits, and underscores. Making all letters in the name lowercase is recommended as it makes
your M-files portable between platforms.



Flow Control

MATLAB has several flow control constructs:

     1.   if
     2.   continue
     3.   break
     4.   switch and case
     5.   for
     6.   while

If

    The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of alternate
groups of statements. An end keyword, which matches the if, terminates the last group of
statements. The groups of statements are delineated by the four keywords--no braces or brackets
are involved.



                               IF expression
                                    statements
                               ELSEIF expression
                                    statements
                               ELSE
                                    statements
                               END


Continue

   The continue statement passes control to the next iteration of the for or while loop in
which it appears, skipping any remaining statements in the body of the loop. In nested loops,
continue passes control to the next iteration of the for or while loop enclosing it.

Break

The break statement lets you exit early from a for or while loop. In nested loops, break exits
from the innermost loop only.


                                                                                             30
CHAPTER 5: Programming


Switch and Case

    The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching case
is executed. There must always be an end to match the switch.



                        SWITCH expression
                        CASE expression
                             statements
                        CASE expression
                             statements
                        OTHERWISE
                             statements
                        END



For

   The for loop repeats a group of statements a fixed, predetermined number of times. A
matching end delineates the statements.



                    FOR variable = expression
                         Statements, ...
                         Statements
                    END



While
    The while loop repeats a group of statements an indefinite number of times under control of a
logical condition. A matching end delineates the statements.


                    WHILE expression
                         Statements
                    END




                                                                                              31