matlab materials

Upload: r-wah-larounette

Post on 04-Jun-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 MATLAB Materials

    1/37

    Introduction to MATLAB

    GENG 200Introduction to Programming

    Faculty of Engineering, ERU

  • 8/13/2019 MATLAB Materials

    2/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 2

    Introduction Programming Introduction to MATLAB Chapter X

    Introduction to MATLAB

    Table of Contents

    1. Getting Started with MATLAB ........................................................................................... 3

    1.1 Introduction ................................................................................................................ 3

    1.2 Graphical User Interface ........................................................................................... 3

    1.3 Help Menu .................................................................................................................. 4

    1.4 Basic Data Manipulation ........................................................................................... 5

    1.4.1 Simple variables and data assignments ............................................................... 5

    1.4.2 Scripts (M-Files) .................................................................................................... 6

    2. Vectors .................................................................................................................................... 8

    2.1 Creating Vectors .................................................................................................................. 8

    2.2 Operations on Vectors ....................................................................................................... 11

    2.1.1 Arithmetic Operations ........................................................................................ 11

    2.1.2 Logical Operations .............................................................................................. 12

    2.1.3 Applying Library Functions ............................................................................... 13

    3. MATLAB Arrays (Matrices) .............................................................................................. 16

    3.1 Creating an Array .................................................................................................... 16

    3.2 Operations on Arrays .............................................................................................. 18

    3.2.1 Arithmetic Operations ........................................................................................ 18

    3.2.2 Applying Library Functions ............................................................................... 23

    4. Execution Control ................................................................................................................ 26

    4.1 Relational and Logical Operators .......................................................................... 26

    4.2 if Statements ............................................................................................................. 26

    4.3 whileLoop .............................................................................................................. 27

    4.4 forLoop .................................................................................................................. 29

    5. User Defined Functions ....................................................................................................... 30

    6. 2-D Plots ............................................................................................................................... 32

    6.1 Basic 2-D Plots .......................................................................................................... 33

    6.2 Subplots .................................................................................................................... 36

  • 8/13/2019 MATLAB Materials

    3/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 3

    Introduction Programming Introduction to MATLAB Chapter X

    1. Getting Started with MATLAB1.1 IntroductionMATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical

    software package, which is used extensively in both academia and industry. It is high-

    level technical computing language and interactive environment for algorithm

    development, data visualization, data analysis, and numeric computation.

    As one can guess from its name, MATLAB deals mainly with matrices. A scalar is a 1-

    by-1 matrix and a row vector of length say 10, is a 1-by-10 matrix. We will elaborate

    more on these and other features of MATLAB in the sections that follow.

    1.2 Graphical User InterfaceMATLAB uses several display windows (see Figure 1.1). The default view includes

    command window, current directory, workspace, and command history windows.

    Figure 1.1 MATLAB Default Window Configuration

    Command Window

    Current Directory

    Workspace Window

    Command History

  • 8/13/2019 MATLAB Materials

    4/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 4

    Introduction Programming Introduction to MATLAB Chapter X

    Command Window: This window offers an environment similar to scientific calculator,

    which will help you in performing fast experiments of your commands and finds out the

    results of fragments of your code.

    Command History: This window will save a record of your commands you issued in the

    command window.

    Workspace Window: This window will show the variables you have defined, and it will

    keep track of them. When you open MATLAB every time this window will be empty

    because you arent defining any variables yet.

    Current Directory: MATLAB accesses files and saves information to a location on your

    hard drive given by the current directory.

    1.3Help MenuThe MATLAB help menu is very powerful. It contains detailed description of every

    command used in MATLAB along with illustrative examples to show the user theexplanation of the command and how it can be used.

    To access the help menu, from the help tab select Product Help. Then you can search for

    any command to get detailed information. See Figure 1.2 which shows the details of the

    sin function.

    Figure 1.2 The Help Menu 1

    Type the phrase you

    want to search for

  • 8/13/2019 MATLAB Materials

    5/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 5

    Introduction Programming Introduction to MATLAB Chapter X

    1.4 Basic Data Manipulation1.4.1 Simple variables and data assignmentsMATLAB presents very easy environment for defining simple variables. Remember that

    any simple variable (scalar) is considered as a 1-by-1 matrix.

    Now, if you want to define a variable in MATLAB just go directly to the command

    window where you will see the prompt (>>) and type the variable name and assign a

    numerical value and press Enter button. When your command is executed, the MATLAB

    will respond by showing you the result of calculation.

    Note 1: If you are doing calculation without assigning the output to a variable (see

    example 1.1), the output will be assigned to a variable called anscreated by MATLAB

    itself.

    Note 2:MATLAB is case sensitive. That is: x + yis not the same as X + y

    The command window can be used to type and execute all MATLAB commands. Also it

    can be used as a scientific calculator to perform simple and complex operations.

    Example 1.1: Calculate: 5*2*(64+2). Type in the numbers and hit Enter

    >> 5*2*(6^4+2)

    ans =

    12980

    Example 1.2: Calculate: x*y+3; where x = 3, y = 4

    >> x = 3

    x =

    3

    >> y = 4

    y =

    4

    >> x*y+3

    ans =

    15

    After doing the previous examples, look at the workspace window. You will see the

    variables and results there as shown in Figure 1.3.

    Note 3:The following commands are useful

    clc: clears the command window

    clear: removes the variables from the workspace

  • 8/13/2019 MATLAB Materials

    6/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 6

    Introduction Programming Introduction to MATLAB Chapter X

    Figure 1.3 Variables added in the Workspace

    Example 1.3: Calculate the volume of a cylinder if height = 10 cm, radius = 5 cm

    using:

    v = height**radius2

    >> h = 10 % height

    h =

    10

    >> r = 5 % radiusr =

    5

    >> v = h*pi*r^2 % volume

    v =

    785.3982

    In the previous example, as you can see that the symbol (%) is used for documentation

    and the constant is defined in MATLAB as pi.

    1.4.2 Scripts (M-Files)MATLAB uses text files for saving scripts (set of instructions) and executing them rather

    than just entering the commands in the command window. It uses its own editor to create

    those text files with the extension .m, and referred to as m-files. You can create m-fileby

    choosing:

    File>New>M-File (or by clicking on the new icon on the far left of the MATLABs

    toolbar).

    Once you created your m-file, you need to save it so that you can run and refer to it in

    future. However, in order to run the m-file it should be in the current directory of the

    MATLAB.

    Let us redo example 1.3 but this time using m-file. Create a new m-file (by selecting

    File>New>M-File) and fill in the commands as shown in Figure 1.4. Save the m-file as

    volume.m

  • 8/13/2019 MATLAB Materials

    7/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 7

    Introduction Programming Introduction to MATLAB Chapter X

    To execute the volume.m, press F5 or from debug menu select run or from toolbar of the

    m-file press on the green play button (or you can write the name of the m-file on the

    command line and press Enter key, so in this example: >>volume).

    Figure 1.4 M-File for calculating the volume of a cylinder

    Note 4:Terminate any line with semicolon (;) to suppress the output

    Example 1.5: Write m-file to calculate the roots of the quadratic equation:

    f(x) = a*x

    2

    + b*x + c; where: a, b, and c are constants and a 0.

    % This m-file to calculate the roots of any quadratic% equation of the form% f(x) = a*x^2 + b*x + c% Use the discriminant to find x1 and x2clearclc% Define the coeff: a, b and ca = 2;b = 4;

    c = 1;% Calculate the Roots: x1, x2x1 = (-b - sqrt(b^2-4*a*c))/(2*a)x2 = (-b + sqrt(b^2-4*a*c))/(2*a)

    When you run the m-file. The roots calculated will be:

    x1 =-1.7071

    X2 =-0.2929

    To Run

    Remove the semicolon to display the

    value of v on the command window

  • 8/13/2019 MATLAB Materials

    8/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 8

    Introduction Programming Introduction to MATLAB Chapter X

    33 41 44 78 89 91

    2. Vectors2.1Creating VectorsA vector is one-dimensional matrix (array) as shown in Figure 2.1 which contains data

    items such as: numbers. Individual items in a vector are usually referred to as elements.Vector elements have two properties: their numerical valuesandposition(index)making

    them unique in a specific vector.

    Value: . . .

    Index: 1 2 3 4 n-1 nFigure 2.1 A vector

    There are many different ways to create a vector. The following shows how to create a

    vector:

    Entering the values directlyvariable_name = [type vectors elements here]

    For example: a = [2, 4, 6, 8]. The commas are optional and can be omitted,

    that is you can write: a = [2 4 6 8].

    Creating a vector with constant spacing by using colon operator (:)variable_name = [first element: spacing : Last element]

    For example: x = [1:2:10].Note that the brackets are optional and the spacing

    can be omitted if the increment you need is 1.

    Using the linspace() function to create a fixed number of values betweentwo limits. variable_name = linspace(xi, xf, n).

    Where xi: initial limit, xf: final limit and n: number of numbers of values in the

    vector.

    For example: x = linspace(0,10,6)

    Using built-in function such as: ones(1,n),zeros(1,n), andrand(1,n). We will discuss the use of these functions in the following

    examples.

    Example 2.1: Entering values directly

    >> x = [2 4 6 8]

    x =2 4 6 8

    >> a = [4, 10, 12, 20]

    a =

    4 10 12 20

  • 8/13/2019 MATLAB Materials

    9/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 9

    Introduction Programming Introduction to MATLAB Chapter X

    Example 2.2: Using the colon operator

    >> m = [0:2:10] % vector of 1-by-6m =

    0 2 4 6 8 10

    >> w = 1:2:10 % vector of 1-by-5

    w =

    1 3 5 7 9

    Example 2.3: Using linespace() function

    >> x = linspace(0,10,6)

    x =

    0 2 4 6 8 10

    >> y = [linspace(0,10,3)]

    y =

    0 5 10

    >> z = [linspace(0,10,4)]z =

    0 3.3333 6.6667 10.0000

    >> cd=6;e=3;h=4;

    >> arr = [e cd*h cos(pi/3) h^2 sqrt(h*h/cd) 14]

    arr =

    3.0000 24.0000 0.5000 16.0000 1.6330

    14.0000

    Example 2.4: Creating vectors using zeros, onesand randfunctions

    % rand(1,n) create a 1-by-n vector of random numbers

    % between 0 and 1

    % Ones(1,n) create a 1-by-n vector of ones

    % zeros(1,n)create a 1-by-n vector of zeros

    >> a=rand(1,4)

    a =

    0.2416 0.9127 0.8257 0.4445

    >> b=ones(1,4)

    b =

    1 1 1 1

    >> c=zeros(1,4)

    c =

    0 0 0 0

    Three variables are defined

    Elements are defined using

    mathematical expressions

  • 8/13/2019 MATLAB Materials

    10/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 10

    Introduction Programming Introduction to MATLAB Chapter X

    Sometimes there is a need to generate random numbers that are distributed in an interval

    other than (0, 1), or to have numbers that are only integers.

    Random numbers that distributed in a range (a, b) can be obtained by the following

    equation (1-by-n vector of random numbers between a and b):

    variable_name = (b-a)*rand(1,n)+a

    Example 2.5: Generate a 1-by-5 vector random numbers between 0 and 10

    >> a=0;b=10;

    >> x = (b-a)*rand(1,5)+a

    x =

    6.7273 6.1865 0.0685 7.4023 9.9174

    Random numbers that are all integers can be generated using rand()with round()

    function. See the following example.

    Example 2.6: Generate a 1-by-10 vector of integer random numbers from 1 to 100

    >> a=1;b=100;>> x = round((b-a)*rand(1,10)+a)

    x =

    93 50 61 1 59 78 66 53 83 96

    Indexing and Accessing a Vector

    The elements of a vector can be accessed by enclosing the index of the required elements

    in parenthesis. For example: X(3)would return the third element.If you attempt to read

    beyond the length of the vector or below index 1, an error will result.

    Example 2.7:

    >> A = [3 4 2 9 0 5]

    A =

    3 4 2 9 0 5

    >> A(1)

    ans =

    3

    >> A(5)

    ans =

    0>> A(0)

    ??? Attempted to access A(0); index must be a positive

    integer or logical.

    >> A(7)

    ??? Attempted to access A(7); index out of bounds because

    numel(A)=6.

    numel(A)returns number of elements in array. An

    equivalent command, for vectors, is length(A)

  • 8/13/2019 MATLAB Materials

    11/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 11

    Introduction Programming Introduction to MATLAB Chapter X

    Note that you can change the value of any element in a vector. In general, you can use:

    A(index) = new_value

    We can also access elements of a vector using the colon operator (:). For example:A(:)

    refers to all elements of the vector A, andA(m:n)refers to elements m through n, n>m.

    2.2

    Operations on Vectors

    2.1.1 Arithmetic OperationsSince all variables in MATLAB are considered as arrays (scalar:11, vector: 1n, array:

    nn) , one should take care of how to perform: multiplication, division and

    exponentiation. On the other hand addition and subtraction have the syntax exactly as

    one would expect.

    The first set of operations with vectors is element-by-element operations, not array

    operations, and hence, linear algebra rules do not apply in this case. Therefore, new set of

    symbols is required. For multiplication we will use (.*), for division we will use (./)and for exponentiation we will use (.^). Note that the new set is using the dot to

    represent that the operation is element-by-element operation. Consider the following

    examples.

    Note 5: vector by vector operation requires that both vectors should be of the same

    length. That is, they have the same number of elements.

    Example 2.8:

    >> A = [4 5 2 10]

    A =

    4 5 2 10

    >> B = [1 0 3 8]

    B =

    1 0 3 8

    >> A + 5

    ans =

    9 10 7 15

    >> A.*2

    ans =

    8 10 4 20>> A*B

    ??? Error using ==> mtimes

    Inner matrix dimensions must agree.

    >> A.*B

    ans =

    4 0 6 80

    >> A^2

    ??? Error using ==> mpower

  • 8/13/2019 MATLAB Materials

    12/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 12

    Introduction Programming Introduction to MATLAB Chapter X

    Matrix must be square.

    >> A.^2

    ans =

    16 25 4 100

    >> A*A

    ??? Error using ==> mtimes

    Inner matrix dimensions must agree.

    >> A.*A

    ans =

    16 25 4 100

    2.1.2 Logical OperationsWe can perform logical operations using relational operators (we will discuss logical

    operators in the coming sections) listed in table 2.1. Those operations can producenumerical or logical results.

    As with arithmetic operations, logical operations can be carried out element-by-element

    on two vectors as long as both vectors are of the same length. Consider example 2.9.

    Example 2.9:

    >> A = [3 6 2 0 1 8 10]

    A =

    3 6 2 0 1 8 10

    >> B = [1 2 3 4 5 6 7]

    B =

    1 2 3 4 5 6 7

    >> A >= 5

    ans =

    0 1 0 0 0 1 1

    >> A(A >= 5)

    ans =

    6 8 10

    Table 2.1 Relational Operators in MATLAB

    Operator Description

    < Less than

    Greater than

    >= Greater than or equal to

    == Equal to

    ~= Not equal to

    Return where A is greater than or equal to 5

    Return elements that are greater than or equal to 5

  • 8/13/2019 MATLAB Materials

    13/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 13

    Introduction Programming Introduction to MATLAB Chapter X

    >> A>=B

    ans =

    1 1 0 0 0 1 1

    Note 6: An alternative to using indexing into the vector using the logical expression is touse the findfunction. For example:find(A>=5)willreturn where A is greater than

    or equal to 5.

    2.1.3 Applying Library FunctionsMATLAB provides rich collection of mathematical functions that cover mathematical,

    trigonometric, and statistical operations. For the partial list of functions go to the

    command window and type the following help commands:

    >>help elfun %List of elementary mathematical functions

    >>help specfun %List of specialized math functions

    >>help elmat %List of elementary matrices functions

    We will explain the following functions because they provide specific capabilities that

    are frequently used.

    sum(A)andmean(A)calculate the sum and mean of the vector A respectively.min(A) andmax(A) return two outputs, the minimum or maximum value in a

    vector and the position (index) where that value occurred.

    Example 2.10:

    >> A = [-1 6 2 0 1 8 10]

    A =

    -1 6 2 0 1 8 10

    >> sum(A)

    ans =

    26

    >> mean(A)

    ans =

    3.7143

    >> [max i] = max(A)

    max =10

    i =

    7

    >> [min i] = min(A)

    min =

    -1

    i =

    1

    Return where each element of A that is not less

    than the corresponding elements of B

  • 8/13/2019 MATLAB Materials

    14/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 14

    Introduction Programming Introduction to MATLAB Chapter X

    Example 2.11: Voltage Divider

    When several resistors are connected in an electrical circuit in series, the voltage across

    each resistor is given by:

    Where Vnand Rnare the voltage across resistor n and its resistance, respectively. Req=sum of all resistors, is the equivalent resistance, and Vsis the source voltage. The power

    dissipated in each in each resistor is given by:

    The figure below shows a circuit with seven resistors connected in series.

    Write a MATLAB program in m-file that calculates voltage across each resistor and the

    power dissipated in each resistor. Also calculate total power dissipated in all resistors and

    the current that flows in circuit using Ohm law: current = Vs/Req. Consider the following

    values:

    Vs = 24 V, R1 = 20, R2 = 14 , R3 = 12, R4 = 18, R5 = 8, R6 = 15, R7 = 7.

    Solution: The following m-file is also shown in figure 2.1

    clear;clc% Define values of the voltage source and all resistors.Vs=24; R1=20;R2=14;R3=12;R4=18;R5=8;R6=15;R7=10;% Define a vector RnRn = [R1 R2 R3 R4 R5 R6 R7];

    % Calculate the equivalent resistorReq = sum(Rn);% Apply the Volatge Divider RuleVn = Rn*Vs/Req% Calculate the power in each resistorPn = Rn*Vs^2/Req^2% Calculate the current using ohm law I = V/RI = Vs/Req% Calculate the total power

    s

    R1 R2 R3

    R4

    R5R6R7

  • 8/13/2019 MATLAB Materials

    15/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 15

    Introduction Programming Introduction to MATLAB Chapter X

    totalPower = sum(Pn)The command window where the m-file was executed:

    Vn =

    4.9485 3.4639 2.9691 4.4536 1.9794 3.7113 2.4742

    Pn =

    1.2244 0.8571 0.7346 1.1019 0.4897 0.9183 0.6122

    I =0.2474

    totalPower =

    5.9381

    Figure 2.1 M-file of voltage divider (example 2.11)

    To Run

  • 8/13/2019 MATLAB Materials

    16/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 16

    Introduction Programming Introduction to MATLAB Chapter X

    3. MATLAB Arrays (Matrices)In the previous section we saw that vector is a simple way to group a collection of similar

    data items. Let us now extend the idea to include arrays confined to two dimensional

    arrays.

    Figure 2.2 shows a typical two dimensional array A with m rows and n columns and A a

    transpose array of A with n rows and m columns. A transposed array is obtained by

    interchanging the values of in rows and columns. To transpose an array in MATLAB you

    can use the apostrophe character () placed after the array:A_tarnspose = A.Note

    that you can obtain a transpose of a vector in the same way.

    [ ] [

    ]

    Figure 2.2 An Array and Its Transpose

    3.1 Creating an ArrayAs with vectors, you can create arrays in MATLAB using many different ways. The

    following summaries most common techniques:

    You can enter the values directly using semicolon to indicate the end of a row. Forexample:A = [2 4 6; 1 3 5],Ais 2 x 3array. The functions zeros(m, n)and ones(m, n)create creates arrays with m rows

    and n columnsfilled with zeros and ones respectively.

    The function rand(m, n)create an array filled with random numbers in the rangefrom 0 to 1.

    The function diag(A) whereA an array, returns its diagonal as a column vector,and diag(B)where Bis a vector, returns a square array of zeros and its diagonal is

    that vector B.

    The functionmagic(m), which creates a square array of sizem x m filled withnumbers from 1 to m2 organized in such a way that its rows, columns, and

    diagonals all add up to the same value.

  • 8/13/2019 MATLAB Materials

    17/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 17

    Introduction Programming Introduction to MATLAB Chapter X

    Example 3.1:

    >> A = [2 4 6; 8 10 12]

    A =

    2 4 6

    8 10 12

    >> A = [2 4; 6 8]

    A =

    2 4

    6 8

    >> B=zeros(3,3)

    B =

    0 0 0

    0 0 0

    0 0 0>> C = [ones(2,2) zeros(2,2)]

    C =

    1 1 0 0

    1 1 0 0

    >> rand(3,4)

    ans =

    0.1067 0.7749 0.0844 0.8001

    0.9619 0.8173 0.3998 0.4314

    0.0046 0.8687 0.2599 0.9106

    Example 3.2:

    >> A = [2 3 4; 7 8 9]

    A =

    2 3 4

    7 8 9

    >> diag(A)

    ans =

    2

    8

    To access a specific element in an 2D array, just indicate the row and column of the

    specified element, i.e.,A(row,col). Also the colon operator can be used to access

    array elements. The following notations illustrate some of the different cases:

    A(:,n)Refers to all elements in all rows of a column nof the arrayA.

    A(n,:)Refers to all elements in all columns of a row nof the arrayA.

    A(:,m:n)Refers to all elements in all rows between columnsmand nof the arrayA.

  • 8/13/2019 MATLAB Materials

    18/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 18

    Introduction Programming Introduction to MATLAB Chapter X

    3.2 Operations on ArraysIn this section we are going to discuss operations performed on arrays involving the basic

    arithmetic operations, library functions and built-in functions.

    However, arithmetic operations can be done in two ways. One way, which usesstandard

    symbols(*, /, and ^), follows the rules of linear algebra. The second way, which is called

    element-by-elementoperations (.*, ./, and .^). In addition, in both types of calculations,

    MATLAB has left division (\ or .\) which are explained later.

    3.2.1 Arithmetic OperationsAddition and Subtraction:Standard addition or subtraction can be done on arrays of identical size (the same number

    of rows and columns). Also can be done when we want to add (subtract) a scalar value to

    an array.

    When two arrays are involved, the sum (or difference) is performed by adding ( or

    subtracting) their corresponding elements. But when a scalar (number) is involved, that

    number is added (or subtracted from) all the elements of the array. Consider the

    following examples.

    Example 3.3:

    >> A = [2 4 1; 3 9 5]

    A =

    2 4 1

    3 9 5

    >> B = [1 2 3; 4 5 6]

    B =

    1 2 3

    4 5 6

    >> A - B

    ans =

    1 2 -2

    -1 4 -1

    >> A + B

    ans =

    3 6 4

    7 14 11

    >> A + 1

    ans =

  • 8/13/2019 MATLAB Materials

    19/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 19

    Introduction Programming Introduction to MATLAB Chapter X

    3 5 2

    4 10 6

    >> B - 1

    ans =

    0 1 2

    3 4 5

    Multiplication:

    The multiplication * of arrays is executed by MATLAB according to the rules of linear

    algebra (This is known as matrix multiplication). This means that if A*B is to be

    executed. Then the number of columns in matrix A should equalto the number of rows

    in matrix B. The result is a matrix that has the same number of rows as A and the same

    number of columns as B. For example: if A4x3*B3x2will result in a new matrix C4x2. This

    means that A*B B*A.

    C4x2 = A4x3*B3x2

    Consider the following example.

    Example 3.4:

    >> A=[1 2 3; 4 5 6;7 8 9] %3x3

    A =

    1 2 3

    4 5 6

    7 8 9

    >> B=[2 3 ;-4 7;5 5]%2x3B =

    2 3

    -4 7

    5 5

    >> A*B

    ans =

    9 32

    18 77

    27 122

    >> B*A??? Error using ==> mtimes

    Inner matrix dimensions must agree.

    Division:

    MATLAB has two types of array division. Which are right division ( / ) and left division

    ( \ ). But before we can start with these operations let us define two terms: IdentityMatrix

    and I nverseof a matrix.

  • 8/13/2019 MATLAB Materials

    20/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 20

    Introduction Programming Introduction to MATLAB Chapter X

    I dentity Matrixis a square matrix in which the diagonal elements are 1s and the rest of

    the elements are 0s.When the identity matrix multiplies another matrix (multiplication

    should be done according to linear algebra), that matrix is unchanged. That is: A*I =

    I*A=A. The identity matrix can be generated in MATLAB using eye(n) which will

    createn x n

    identity matrix.

    I nverse of a matrixis best explained using the following illustration. The matrix B is the

    inverse of matrix A if when the two matrices are multiplied product is the identity matrix.

    Both matrices mustbe square and the order can be A*B or B*A. The inverse of matrix A

    can be written as A-1. In MATLAB you can find the inverse using the two commands:

    inv(A) or raise to the power of -1, that is:A^-1. The following example illustrates

    both identity and inverse matrices.

    Example 3.5: Inverse and Identity Matrices

    >> A=[2 1 4;4 1 8;2 -1 3] %Create the MatrixA =

    2 1 4

    4 1 8

    2 -1 3

    >> B=inv(A)%use inv() to find the inverse of A

    B =

    5.5000 -3.5000 2.0000

    2.0000 -1.0000 0

    -3.0000 2.0000 -1.0000

    >> A*B %multiplication of A and B gives the Identity Matrix

    ans =

    1 0 0

    0 1 0

    0 0 1

    >> A^-1 % use power of -1 to find the inverse of A

    ans =

    5.5000 -3.5000 2.0000

    2.0000 -1.0000 0-3.0000 2.0000 -1.0000

    >> B-A^-1

    ans =

    0 0 0

    0 0 0

    0 0 0

  • 8/13/2019 MATLAB Materials

    21/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 21

    Introduction Programming Introduction to MATLAB Chapter X

    Right divisionis used to solve the matrix equation XC = D. In this equation X and D are

    row vectors. It can be solved by multiplying on the right both sides by the inverse of C:

    X C C-1= D C-1

    X = D C-1

    In MATLAB, the last equation can be written as:X = D/C

    Left divisionis used to solve the matrix equationAX = B. In this equation X and B are

    row vectors. It can be solved by multiplying on the left both sides by the inverse of A:

    A A-1 X = A-1B

    X = A-1B

    In MATLAB, the last equation can be written as: X = A\B. The following example

    illustrates both left and right divisions to solve a set of linear equations.

    Example 3.6: A Set of Linear Equations

    Use matrix operation to solve the following set of linear equations: See the solution on the next page.

  • 8/13/2019 MATLAB Materials

    22/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 22

    Introduction Programming Introduction to MATLAB Chapter X

    Solution: Using the rules explained earlier, the above system of equation can be written

    in matrix form AX=B or XC=D. (Note that this example can be solved using inv()

    function)

    [ ] [] [ ] []>> A=[4 -2 6;2 8 2;6 10 3] %Solving using the form AX=B

    A =

    4 -2 6

    2 8 2

    6 10 3

    >> B = [8;4;0]

    B =

    8

    4

    0

    >> X=A\B

    X =

    -1.8049

    0.2927

    2.6341

    >> C=[4 2 6;-2 8 10;6 2 3] %Solving using the form XC=DC =

    4 2 6

    -2 8 10

    6 2 3

    >> D=[8 4 0]

    D =

    8 4 0

    >> Xc=D/C

    Xc =

    -1.8049 0.2927 2.6341

    Note the difference between A and C

    X and Xc are transpose of each other

  • 8/13/2019 MATLAB Materials

    23/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 23

    Introduction Programming Introduction to MATLAB Chapter X

    Element-By-Element Operations

    These operations are carried out on each element of the array. Note that these operations

    are performed on arrays of the same size.

    Symbol Description Symbol Description

    .* Multiplication ./ Right Division

    .^ Exponentiation .\ Left Division

    Example 3.7:

    >> A=[1 2 3;4 5 6] % Define 2x3 array A

    A =

    1 2 3

    4 5 6

    >> B=[5 7 4;6 2 9] % Define 2x3 array BB =

    5 7 4

    6 2 9

    >> A*B

    ??? Error using ==> mtimes

    Inner matrix dimensions must agree.

    >> A.*B

    ans =

    5 14 12

    24 10 54>> A./B

    ans =

    0.2000 0.2857 0.7500

    0.6667 2.5000 0.6667

    >> A.^2

    ans =

    1 4 9

    16 25 36

    3.2.2 Applying Library FunctionsThe built-in functions applied to arrays as an element-by-element operation in which the

    input is an array and the output is also an array in which each element is calculated by

    applying the function to each element of the input array. For example, executing the

    command cos(A)will result in another array of same size asAwith each element is the

    cosine of the corresponding element inA. Consider the following example.

  • 8/13/2019 MATLAB Materials

    24/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 24

    Introduction Programming Introduction to MATLAB Chapter X

    Example 3.8:

    >> A=[1 5 70;pi 2*pi 3*pi] % Define 2x3 array A

    A =

    1.0000 5.0000 70.0000

    3.1416 6.2832 9.4248

    >> sin(A) % Apply the sin function

    ans =

    0.8415 -0.9589 0.7739

    0.0000 -0.0000 0.0000

    >> sqrt(A) % Apply the sqrt function

    ans =

    1.0000 2.2361 8.3666

    1.7725 2.5066 3.0700

    As said before, MATLAB has a large built-in Library functions. For example: sum(A):

    treats the columns ofAas vectors, returning a row vector of the sums of each column,

    det(A):return the determinant of a square arrayA, std(A):returns a row vector

    containing the standard deviation of the elements of each column ofA. You can use

    MATLAB help window for a complete list of all functions. Note that these functions can

    be applied to vectors.

    Example 3.9:>> A=[2 4 6;3 5 7; 1 2 3]

    A =

    2 4 6

    3 5 7

    1 2 3

    >> sum(A) % Apply the sum function

    ans =

    6 11 16

    >> std(A) % Apply the standard deviation function

    ans =1.0000 1.5275 2.0817

    >> sort(A) % Sorting array in an ascending order

    ans =

    1 2 3

    2 4 6

    3 5 7

    >> det(A) % Calculating the determinant

  • 8/13/2019 MATLAB Materials

    25/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 25

    Introduction Programming Introduction to MATLAB Chapter X

    0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1

    0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-8

    -6

    -4

    -2

    0

    2

    4

    6

    8

    0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-6

    -4

    -2

    0

    2

    4

    6

    8

    ans =

    0

    Example of MATLAB Application - Amplitude modulation (AM):

    AM is a technique used in electronic communication, most commonly for transmitting

    information via a radio carrier wave. AM works by varying the strength of thetransmitted signal in relation to the information being sent. For example, changes in the

    signal strength can be used to reflect the sounds to be reproduced by a speaker, or to

    specify the light intensity of television pixels. The AM signal is given by the following

    formula: () () ()Wherem(t)is the message signal to be transmitted such as speech signal and fcis the

    frequency of the cosine (carrier) signal.

    Write a MATLAB m-file to simulate the AM single s(t)with the following parameters:

    t: time vector from 0 to 1 with step of 0.001

    fc: 15 Hz

    m(t): cosine signal with frequency of 5 Hz and amplitude of 8 volt

    Solution:

    % THIS M-FILE IS TO SIMULATE AMPLITUDE MODULATION SIGNAL% GIVEN BY: S(T)=M(T)*COS(2*PI*Fc*T)

    %time vector from 0 to 1 with step 0.001t=0:0.001:1;% Carrier signalvc = cos(2*pi*15*t);

    % transmitted signalm = 8*cos(2*pi*5*t);% AM signals = m.*vc;% Plotting the signalsfigure(1)plot(t,vc)figure(2)plot(t,m)figure(3)plot(t,s)

    figure(n)command opens a new figure window

    with number specified by n

    plot(t,x)command will plot x vs. t such that t

    and x are of the same length or size

  • 8/13/2019 MATLAB Materials

    26/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 26

    Introduction Programming Introduction to MATLAB Chapter X

    4. Execution ControlIn this section we are going to study some MATLAB structures used to weather execute a

    set of instructions or not, and how many times those set is going to be executed. Also we

    are going to discuss how to process 1-D and 2-D arrays with some of those structures.

    Specifically, the control structure covered here are: if-statements,whileloop and for

    loop.

    4.1 Relational and Logical OperatorsWe have discussed the use of relational operators previously in section 2.1.2. The logical

    operators in MATLAB are listed in table 4.1.

    Table 4.1 Logical Operators in MATLAB

    Logical Operator Name Description

    & AND Operates on two operands (A&B). If both results are true,

    the result is true. Otherwise the result is false| OR Operates on two operands (A|B). If either one or both

    are true, the result is true. Otherwise, the result is false

    ~ NOT Operates on one operand (~A). The result is true if theoperand is false and false if the operand is true

    Note: The logical operators AND and OR listed above are element-by-element operators.

    That is, if the both operands are arrays, then they have to be of the same size. The

    outcome is an array of the same size with 1s and 0s according to the output of the

    operation at each position.

    4.2 if Statementsifevaluates a logical expression and executes a block of statements based on whether

    the logical expressions evaluates to true (logical 1) or false (logical 0). The general

    structure is as follows.

    iflogical_expression 1

    statements

    elseiflogical_expression 2

    statements

    .

    .

    .

    elseiflogical_expression n

    statements

    else

    default statements

    end

  • 8/13/2019 MATLAB Materials

    27/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 27

    Introduction Programming Introduction to MATLAB Chapter X

    If the logical_expression evaluates as true (logical 1), then the block of

    statements that follow if logical_expression are executed, otherwise the

    statements are skipped and program control is transferred to the eleseif

    logical_expression 2. If it is evaluated as true then the statements that

    follow it are executed, and so on so forth. Now, if none of the logical expressionsare

    true, then the control is transferred to the else statement and the defaultstatementsare executed.

    Note: The only essential part of the general structure explained above is the first if

    statement, the statements that follow it, and the end statement. All other parts can be

    added according to the logic requirements.

    Example 4.1: Even or Odd

    clear;clc;n = 9;ifround(n/2) == n/2

    disp('Even') % disp('...') used to display textelse

    disp('Odd')end

    Note that in the previous example, the function disp(...)is used to display a text.

    Actually, this function can also be used to display an array without printing its name, for

    example: disp(A), whereAis an array. Also that we can rewrite the previous example

    such that the m-file will ask the user to enter a number. We can do that by using the

    function input(), i.e. n=input(Enter an Integer:), then this message will

    appear on the command line waiting for the user to enter a number and then assigns the

    value to n.

    Example 4.2:

    clc;clear;n = input('Enter an integer number: ');ifround(n/2) == n/2

    disp('Even') % disp('...') used to display textelse

    disp('Odd')end

    4.3 whileLoopAs in any programming language, the while loop is used to execute a set of statements

    many times (each time is called iteration or loops) until a specified condition is satisfied.

    The general structure of the while loop is as follows:

  • 8/13/2019 MATLAB Materials

    28/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 28

    Introduction Programming Introduction to MATLAB Chapter X

    whilelogical_expression

    statements

    end

    The following examples illustrate the use of a while loop using m-file.

    Example 4.3: Generate a sequence of even numbers

    clc;clear;x=2whilex>=2 & x

  • 8/13/2019 MATLAB Materials

    29/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 29

    Introduction Programming Introduction to MATLAB Chapter X

    4.4 forLoopThe for loop is used to repeat a set of statements fixed number of times. The general

    structure is as follows:

    fori = initial_value : step_size : final_value

    statements

    end

    Note: the step size can be negative, but in this case the initial value should be greater

    than final value. If the step is omitted, then it defaults to one.

    Example 4.5:

    clc;clear;fori=1:3:10

    x=i^2

    endThe output displayed in the command window is:

    x =

    1

    x =

    16

    x =

    49

    x =

    100

    So far, we have been displaying the values in the command line by omitting the

    semicolon operator from the end of each line we wish to display its output. In fact,

    MATLAB has a built-in function that can be used to display and control the format of the

    values displayed in the command line. This function is fprintf(), which is similar

    to the function used in c to do the same operation. The general format of this function is:

    fprintf(format, variable)

    Let us rewrite the previous example using fprintffunction.

    Example 4.6:

    clc;clear;fori=1:3:10x=i^2;fprintf('x = %d\n',x)

    end

    The out displayed in the command window is:

    x = 1

    x = 16

    x = 49

    %d: decimal point notation\n: new line

  • 8/13/2019 MATLAB Materials

    30/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 30

    Introduction Programming Introduction to MATLAB Chapter X

    x = 100

    Example 4.7: a vector is given byA = [-5,-17,-3,8,0,-1,12,-4,-6,6,-7,17].

    Write a m-file that doubles the negative elements that are odd.

    clc;clearA = [-5,-17,-3,8,0,-1,12,-4,-6,6,-7,17];disp('A Before = ')

    disp(A)fori=1:length(A)

    if(A(i)

  • 8/13/2019 MATLAB Materials

    31/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 31

    Introduction Programming Introduction to MATLAB Chapter X

    In this section we are going to discuss how to define user defined functions, how data are

    passed to a function and how data are returned from functions

    Function Definition

    User defined functions must be stored in a separate m-file and in your directory of work.

    And the m-file that contains your function should be saved with same name as the

    function.

    The general definition of a function is as follows:

    function[output_vars] = function_name (input_vars)

    %optional documentation

    function code body

    Note that if you have one output variable, then omit the brackets [ ]. Those only used if

    you have more than output variable. Consider the following two examples.

    Example 5.1: Write a MATLAB function file for f(x) = x2+2x+3. Then calculate f(0) and

    f(3).

    Solution: create a new m-file, save it as f.m and then write your code. Figure 5.1 shows

    the required function.

    You can call the function in the command line using its name as follows:

    >> f(0)ans =

    3

    >> f(6)

    ans =

    51

    Example 5.2: Write MATLAB function to calculate the area and circumference of a

    circle for given radius r.

    Note that the name of the file should

    match the name of the function

  • 8/13/2019 MATLAB Materials

    32/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 32

    Introduction Programming Introduction to MATLAB Chapter X

    We should follow the same steps used in the previous example, but here use another

    name, let us say circle.m. Note that since we have two output variables, they have to be

    enclosed by [].

    function[area,cercom]=circle(radius)%Function to compute area and%circumference of a circlearea = pi*radius^2;cercom = 2*pi*radius;

    The circle function can be used in the command line as follows:

    >> [a,c]=circle(4)

    a =

    50.2655

    c =

    25.1327

    >> [a,c]=circle(1)

    a =

    3.1416

    c =

    6.2832

    6. 2-D Plots

    a: area

    c: circumference

  • 8/13/2019 MATLAB Materials

    33/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 33

    Introduction Programming Introduction to MATLAB Chapter X

    6.1 Basic 2-D PlotsThe most basic and perhaps most useful command for producing a simple 2-D plots is the

    plot() command.

    plot(xvalues, yvalues,style-option)

    where:

    xvaluesand yvaluesare vectors of the same length containing x and y coordinates

    of points on the graph.

    style-option is an optional arguments that specifies the color, the line style (e.g.,

    solid, dashed, dotted,etc.) and the point-marker style (e.g., o, +, *, etc.). All three options

    can be specified together as the syle-option in the general form:

    color_linestyle_markerstyle.

    Style Option

    The style-option in the plot command is a character string that consists of one, two or

    three characters that specify the color and/or line style. There are several color, line and

    marker style option as shown in figure 6.1.

    Table 6.1: Style option for the color, line and marker styles

    Examplesplot(x,y) plots y vs. x with a blue solid line (default)

    plot(x,y,'r') plots y vs. x with a red solid line

    plot(x,y,':') plots y vs. x with a dotted lineplot(x,y,'b--') plot y vs. x with a blue dashed line

    plot(x,y,'+') plot y vs. x as unconnected points marked by +

    Example 6.1: Plot the function y = 3.5-0.5x cos(6x), where -2 x 4 using

    different line styles.

    Color style-option Line style-option Marker style-optiony yellow - solid + plus signm magenta -- dashed o circlec cyan : dotted * asteriskr

    red -. dash-dotx

    x-markg green . point

    b blue ^ up triangle

    w white s square

    k black d diamond

  • 8/13/2019 MATLAB Materials

    34/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 34

    Introduction Programming Introduction to MATLAB Chapter X

    clc;clearx=-2:0.01:4;y=3.5.^(-0.5*x).*cos(6*x);figure(1)plot(x,y)figure(2)

    plot(x,y,'r')figure(3)plot(x,y,':')figure(4)plot(x,y,'b--')figure(5)plot(x,y,'+')

    Also we can plot more than one graph on the same plot by typing pairs of vectors in the

    plot command, for example:plot(x,y,g--x,z,r-.)

  • 8/13/2019 MATLAB Materials

    35/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 35

    Introduction Programming Introduction to MATLAB Chapter X

    Example 6.2:

    clc;clearx=-pi:1/pi:pi;y=cos(x);z=sin(x);

    plot(x,y,'g--',x,z,'r-.')% Add grid linesgrid on% Remove grid lines (uncomment next line)%grid off

    Formatting a Plot

    A figure that contains a plot needs to be formatted to have a specific look and to display

    information in addition to the graph itself. Consider the following commands:

    xlabel(x-axis label)

    ylabel(y-axis label)

    title(title of the figure)

    axis([xmin xmax ymin ymax])

    Example 6.3:

  • 8/13/2019 MATLAB Materials

    36/37

    UAE University, Faculty of Engineering, ERU | Ayman Rabee 36

    Introduction Programming Introduction to MATLAB Chapter X

    clc;cleart = 0:0.001:1;f = 15;y = cos(2*pi*f*t);plot(t,y,'--')xlabel('time (sec)')

    ylabel('cos(2\pift)')title('t vs. cos(2\pift)')grid on

    6.2 SubplotsSometimes it is required to place plots side by side. The command subplot() can be

    used to set and design the required layout.

    subplot(rows,columns,index)

    This function divides the graphics window into rows xcolumnssub-windows and puts a

    certain plot in a position specified by the index. For example the two commands

    subplot(2,2,3), plot(x,y) divides the graphics window into 4 sub-windowsand places the plot of y vs. xin the third sub-window. See example 6.4.

    Example 6.4:

  • 8/13/2019 MATLAB Materials

    37/37

    Introduction Programming Introduction to MATLAB Chapter X

    clc;cleart = -0.5:0.001:0.5;f = 15;x = cos(2*pi*f*t);y = sin(2*pi*f*t);z = sinc(2*pi*f*t);

    w = 0.5*t-0.5;subplot(2,2,1)plot(t,x)grid ontitle('cosine vs. time')subplot(2,2,2)plot(t,y)grid ontitle('sine vs. time')subplot(2,2,3)plot(t,z)grid on

    title('sinc vs. time')subplot(2,2,4)plot(t,w)grid ontitle('w vs. time')

    subplot(2,2

    subplot(2,2

    subplot(2,2

    subplot(2,2