You are on page 1of 37

Introduction to MATLAB

GENG 200 Introduction to Programming Faculty of Engineering, ERU

Introduction Programming

Introduction to MATLAB

Chapter X

Introduction to MATLAB
Table of Contents
1. Getting Started with MATLAB ........................................................................................... 3 1.1 1.2 1.3 1.4 1.4.1 1.4.2 2. Introduction ................................................................................................................ 3 Graphical User Interface ........................................................................................... 3 Help Menu .................................................................................................................. 4 Basic Data Manipulation ........................................................................................... 5 Simple variables and data assignments ............................................................... 5 Scripts (M-Files) .................................................................................................... 6

Vectors .................................................................................................................................... 8 2.1 Creating Vectors .................................................................................................................. 8 2.2 Operations on Vectors ....................................................................................................... 11 2.1.1 2.1.2 2.1.3 Arithmetic Operations ........................................................................................ 11 Logical Operations .............................................................................................. 12 Applying Library Functions ............................................................................... 13

3.

MATLAB Arrays (Matrices) .............................................................................................. 16 3.1 3.2 3.2.1 3.2.2 Creating an Array .................................................................................................... 16 Operations on Arrays .............................................................................................. 18 Arithmetic Operations ........................................................................................ 18 Applying Library Functions ............................................................................... 23

4.

Execution Control................................................................................................................ 26 4.1 4.2 4.3 4.4 Relational and Logical Operators .......................................................................... 26 if Statements ............................................................................................................. 26 while Loop.............................................................................................................. 27 for Loop .................................................................................................................. 29

5. 6.

User Defined Functions ....................................................................................................... 30 2-D Plots ............................................................................................................................... 32 6.1 6.2 Basic 2-D Plots .......................................................................................................... 33 Subplots .................................................................................................................... 36

UAE University, Faculty of Engineering, ERU | Ayman Rabee

Introduction Programming

Introduction to MATLAB

Chapter X

1. Getting Started with MATLAB


1.1 Introduction MATLAB, 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 highlevel 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 1by-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 Interface MATLAB uses several display windows (see Figure 1.1). The default view includes command window, current directory, workspace, and command history windows.

Command Window

Current Directory

Workspace Window Command History

Figure 1.1 MATLAB Default Window Configuration

UAE University, Faculty of Engineering, ERU | Ayman Rabee

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.3 Help Menu The MATLAB help menu is very powerful. It contains detailed description of every command used in MATLAB along with illustrative examples to show the user the explanation 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.

Type the phrase you want to search for

Figure 1.2 The Help Menu 1

UAE University, Faculty of Engineering, ERU | Ayman Rabee

Introduction Programming

Introduction to MATLAB

Chapter X

1.4 Basic Data Manipulation 1.4.1 Simple variables and data assignments

MATLAB 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 ans created by MATLAB itself. Note 2: MATLAB is case sensitive. That is: x + y is 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
UAE University, Faculty of Engineering, ERU | Ayman Rabee 5

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 % radius r = 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-file by 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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

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).

To Run

Remove the semicolon to display the value of v on the command window

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*x2 + 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 x2 clear clc % Define the coeff: a, b and c a = 2; b = 4; c = 1; % Calculate the Roots: x1, x2 x1 = (-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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

Introduction Programming

Introduction to MATLAB

Chapter X

2. Vectors
2.1 Creating Vectors A 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 values and position (index) making them unique in a specific vector. Value: 33 Index: 1
41

44 3

78 4

...

89 n-1

91 n

Figure 2.1 A vector

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

Entering the values directly variable_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 between two 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)

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

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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

Introduction Programming

Introduction to MATLAB

Chapter X

Example 2.2: Using the colon operator >> m = [0:2:10] % vector of 1-by-6 m = 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 >> y = [linspace(0,10,3)] y = 0 5 10 >> z = [linspace(0,10,4)] z = 0 3.3333 6.6667

10

10.0000

Three variables are defined >> 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 Elements are defined using mathematical expressions

Example 2.4: Creating vectors using zeros, ones and rand functions % 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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

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) numel(A) returns number of elements in array. An ans = equivalent command, for vectors, is length(A) 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.

UAE University, Faculty of Engineering, ERU | Ayman Rabee

10

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, and A(m:n) refers to elements m through n, n>m. 2.2 Operations on Vectors

2.1.1 Arithmetic Operations Since 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
UAE University, Faculty of Engineering, ERU | Ayman Rabee 11

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 Operations We can perform logical operations using relational operators (we will discuss logical operators in the coming sections) listed in table 2.1. Those operations can produce numerical or logical results.
Table 2.1 Relational Operators in MATLAB

Operator < <= > >= == ~=

Description Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to

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
Return where A is greater than or equal to 5

>> A(A >= 5) ans = 6 8

Return elements that are greater than or equal to 5

10
12

UAE University, Faculty of Engineering, ERU | Ayman Rabee

Introduction Programming

Introduction to MATLAB Return where each element of A that is not less than the corresponding elements of B

Chapter X

>> A>=B ans = 1

Note 6: An alternative to using indexing into the vector using the logical expression is to use the find function. For example: find(A>=5) will return where A is greater than or equal to 5. 2.1.3 Applying Library Functions MATLAB 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) and mean(A) calculate the sum and mean of the vector A respectively. min(A) and max(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 A = -1 >> sum(A) ans = 26 >> mean(A) ans = 3.7143 >> [max i] max = 10 i = 7 >> [min i] min = -1 i = 1

6 2 0 1 8 10] 6 2 0 1 8 10

= max(A)

= min(A)

UAE University, Faculty of Engineering, ERU | Ayman Rabee

13

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 Vn and Rn are the voltage across resistor n and its resistance, respectively. Req = sum of all resistors, is the equivalent resistance, and Vs is 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.
R1 R2 R3

Vs

R4

R7

R6

R5

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 Rn Rn = [R1 R2 R3 R4 R5 R6 R7]; % Calculate the equivalent resistor Req = sum(Rn); % Apply the Volatge Divider Rule Vn = Rn*Vs/Req % Calculate the power in each resistor Pn = Rn*Vs^2/Req^2 % Calculate the current using ohm law I = V/R I = Vs/Req % Calculate the total power

UAE University, Faculty of Engineering, ERU | Ayman Rabee

14

Introduction Programming

Introduction to MATLAB

Chapter X

totalPower = sum(Pn) The command window where the m-file was executed:
Vn = 4.9485 Pn = 1.2244 I = 0.2474 totalPower = 5.9381 0.8571 0.7346 1.1019 0.4897 0.9183 0.6122 3.4639 2.9691 4.4536 1.9794 3.7113 2.4742

To Run

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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

15

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 Array

As 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. For example: A = [2 4 6; 1 3 5], A is 2 x 3 array. The functions zeros(m, n) and ones(m, n) create creates arrays with m rows and n columns filled with zeros and ones respectively. The function rand(m, n) create an array filled with random numbers in the range from 0 to 1. The function diag(A) where A an array, returns its diagonal as a column vector, and diag(B) where B is a vector, returns a square array of zeros and its diagonal is that vector B. The function magic(m), which creates a square array of size m x m filled with numbers from 1 to m2 organized in such a way that its rows, columns, and diagonals all add up to the same value.

UAE University, Faculty of Engineering, ERU | Ayman Rabee

16

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.9619 0.8173 0.3998 0.0046 0.8687 0.2599 Example 3.2: >> A = [2 3 4; 7 8 9] A = 2 3 4 7 8 9 >> diag(A) ans = 2 8

0.8001 0.4314 0.9106

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 n of the array A. A(n,:) Refers to all elements in all columns of a row n of the array A. A(:,m:n) Refers to all elements in all rows between columns m and n of the array A.

UAE University, Faculty of Engineering, ERU | Ayman Rabee

17

Introduction Programming

Introduction to MATLAB

Chapter X

3.2

Operations on Arrays

In 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 uses standard symbols (*, /, and ^), follows the rules of linear algebra. The second way, which is called element-by-element operations (.*, ./, and .^). In addition, in both types of calculations, MATLAB has left division (\ or .\) which are explained later. 3.2.1 Arithmetic Operations

Addition 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 A = 2 3 >> B = [1 B = 1 4 >> A - B ans = 1 -1 >> A + B ans = 3 7 >> A + 1 ans =

4 1; 3 9 5] 4 1 9 5 2 3; 4 5 6] 2 5 3 6

2 4

-2 -1

6 14

4 11

UAE University, Faculty of Engineering, ERU | Ayman Rabee

18

Introduction Programming

Introduction to MATLAB

Chapter X

3 4 >> B - 1 ans = 0 3

5 10

2 6

1 4

2 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 equal to 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*B3x2 will 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]%2x3 B = 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: Identity Matrix and Inverse of a matrix.
UAE University, Faculty of Engineering, ERU | Ayman Rabee 19

Introduction Programming

Introduction to MATLAB

Chapter X

Identity Matrix is 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 create n x n identity matrix. Inverse of a matrix is 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 must be 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 Matrix A = 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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

20

Introduction Programming

Introduction to MATLAB

Chapter X

Right division is 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 division is used to solve the matrix equation AX = 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-1 B X = A-1 B 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.

UAE University, Faculty of Engineering, ERU | Ayman Rabee

21

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 Note the difference between A and C 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=D C = X and Xc are transpose of each other 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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

22

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 Multiplication Exponentiation Symbol ./ .\ Description Right Division 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 B B = 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 Functions

The 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 as A with each element is the cosine of the corresponding element in A. Consider the following example.

UAE University, Faculty of Engineering, ERU | Ayman Rabee

23

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 of A as vectors, returning a row vector of the sums of each column, det(A): return the determinant of a square array A, std(A): returns a row vector containing the standard deviation of the elements of each column of A. 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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

24

Introduction Programming

Introduction to MATLAB

Chapter X

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 the transmitted 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: () () ( ) Where m(t) is the message signal to be transmitted such as speech signal and fc is 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.001 t=0:0.001:1; % Carrier signal vc = cos(2*pi*15*t); % transmitted signal m = 8*cos(2*pi*5*t); % AM signal s = m.*vc; % Plotting the signals figure(n) command opens a new figure window figure(1) with number specified by n plot(t,vc) figure(2) plot(t,x) command will plot x vs. t such that t plot(t,m) figure(3) and x are of the same length or size plot(t,s)
1 0.8 0.6

8 6 4

0.4 0.2 0 -0.2 -0.4

2
0

0
-2

-2
-4

-0.6 -0.8 -1

-6 -8

-4

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

-6 0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

UAE University, Faculty of Engineering, ERU | Ayman Rabee

25

Introduction Programming

Introduction to MATLAB

Chapter X

4.

Execution Control

In 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, while loop and for loop. 4.1 Relational and Logical Operators We 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
AND OR NOT

Description
Operates on two operands (A&B). If both results are true, the result is true. Otherwise the result is false Operates on two operands (A|B). If either one or both are true, the result is true. Otherwise, the result is false Operates on one operand (~A). The result is true if the operand 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 Statements if evaluates 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. if logical_expression 1 statements elseif logical_expression 2 statements . . . elseif logical_expression n statements else default statements end
UAE University, Faculty of Engineering, ERU | Ayman Rabee 26

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 expressions are true, then the control is transferred to the else statement and the default statements are 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; if round(n/2) == n/2 disp('Even') % disp('...') used to display text else 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), where A is 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: '); if round(n/2) == n/2 disp('Even') % disp('...') used to display text else disp('Odd') end 4.3 while Loop As 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:

UAE University, Faculty of Engineering, ERU | Ayman Rabee

27

Introduction Programming

Introduction to MATLAB

Chapter X

while logical_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=2 while x>=2 & x<=10 x=x+2 end The output displayed in the command window is: x = 2 x = 4 x = 6 x = 8 x = 10 x = 12 Example 4.4: Implied Loop clear;clc; x=[0:0.01:10]; y=sin(x); figure(1) plot(x,y) % to achieve the same result using while loop i = 1; while i<=1001 m = (i-1)*0.01; yy(i)=sin(m); xx(i)=m; % this is to create a time-vector x i = i+1; end figure(2) plot(xx,yy) In example 4.4, the first set is used to create a 1-D array x (vector) using the colon operator and 1-D array y (vector) using the sin() function. Each of them of size 1x1001(10/0.01+1=1001). We can do the same using a while loop. But we have to control how many times the loop will execute using i<=1001 and i=i+1.

UAE University, Faculty of Engineering, ERU | Ayman Rabee

28

Introduction Programming

Introduction to MATLAB

Chapter X

4.4 for Loop The for loop is used to repeat a set of statements fixed number of times. The general structure is as follows: for i = 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; for i=1:3:10 x=i^2 end The 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 fprintf function. Example 4.6: clc;clear; for i=1:3:10 x=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

UAE University, Faculty of Engineering, ERU | Ayman Rabee

29

Introduction Programming

Introduction to MATLAB

Chapter X

x = 100 Example 4.7: a vector is given by A = [-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;clear A = [-5,-17,-3,8,0,-1,12,-4,-6,6,-7,17]; disp('A Before = ') disp(A) for i=1:length(A) if (A(i)<0) & (A(i)/2 ~= round(A(i)/2)) A(i) = A(i)*2; end end disp('A After = ') disp(A) The output displayed in the command line: A Before = -5 -17 A After = -10 -34

-3 -6

8 8

0 0

-1 -2

12 12

-4 -4

-6 -6

6 6

-7 -14

17 17

5. User Defined Functions

UAE University, Faculty of Engineering, ERU | Ayman Rabee

30

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.

Note that the name of the file should match the name of the 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.
UAE University, Faculty of Engineering, ERU | Ayman Rabee 31

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 circle area = 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

a: area c: circumference

6. 2-D Plots

UAE University, Faculty of Engineering, ERU | Ayman Rabee

32

Introduction Programming

Introduction to MATLAB

Chapter X

6.1 Basic 2-D Plots The most basic and perhaps most useful command for producing a simple 2-D plots is the plot() command. plot(xvalues, yvalues,style-option) where: xvalues and yvalues are 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

Color style-option y yellow m magenta c cyan r red g green b blue w white k black Examples plot(x,y) plot(x,y,'r') plot(x,y,':') plot(x,y,'b--') plot(x,y,'+')

Line style-option solid -dashed : dotted -. dash-dot

Marker style-option + plus sign o circle * asterisk x x-mark . point ^ up triangle s square d diamond

plots y vs. x with a blue solid line (default) plots y vs. x with a red solid line plots y vs. x with a dotted line plot y vs. x with a blue dashed line 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.
UAE University, Faculty of Engineering, ERU | Ayman Rabee 33

Introduction Programming

Introduction to MATLAB

Chapter X

clc;clear x=-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-.)
UAE University, Faculty of Engineering, ERU | Ayman Rabee 34

Introduction Programming

Introduction to MATLAB

Chapter X

Example 6.2: clc;clear x=-pi:1/pi:pi; y=cos(x); z=sin(x); plot(x,y,'g--',x,z,'r-.') % Add grid lines grid 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:

UAE University, Faculty of Engineering, ERU | Ayman Rabee

35

Introduction Programming

Introduction to MATLAB

Chapter X

clc;clear t = 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

Subplots

Sometimes 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 x columns sub-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-windows and places the plot of y vs. x in the third sub-window. See example 6.4.

Example 6.4:
UAE University, Faculty of Engineering, ERU | Ayman Rabee 36

Introduction Programming

Introduction to MATLAB

Chapter X

clc;clear t = -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 on title('cosine vs. time') subplot(2,2,2) plot(t,y) grid on title('sine vs. time') subplot(2,2,3) plot(t,z) grid on title('sinc vs. time') subplot(2,2,4) plot(t,w) grid on title('w vs. time')

subplot(2,2,1)

subplot(2,2,2)

subplot(2,2,3)

subplot(2,2,4)

UAE University, Faculty of Engineering, ERU | Ayman Rabee

37

You might also like