Chapter Three: Introduction to MATLAB PDF
Document Details
Uploaded by FeatureRichCedar
Tags
Summary
This document provides an introduction to MATLAB, a high-performance language for technical computing. It covers basic operations like calculations and creating vectors and matrices, alongside plotting techniques. This document also contains information about variables and arrays.
Full Transcript
# Chapter Three: Introduction to MATLAB At the end of this chapter, the students will be able to: - Use MatLab as a calculator (a tool for performing math tasks). - Create a vector in MatLab with different methods. - Create a two-dimensional array in MatLab. - Manipulate data using arrays in MATLA...
# Chapter Three: Introduction to MATLAB At the end of this chapter, the students will be able to: - Use MatLab as a calculator (a tool for performing math tasks). - Create a vector in MatLab with different methods. - Create a two-dimensional array in MatLab. - Manipulate data using arrays in MATLAB. - Write Matlab codes to solve engineering problems. - Perform basic plotting tasks. - Change plot specifics and plot modifications. ## 3.1 What is MATLAB? MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment. Typical uses include: - Math and computation - Algorithm development - Modeling, simulation, and prototyping - Data analysis, exploration, and visualization - Scientific and engineering graphics - Application development, including Graphical User Interface building MATLAB is a commercial product of The MathWorks Company (http://www.mathworks.com/). The name MATLAB stands for Matrix LABoratory. MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. This allows you to solve many technical computing problems, especially those with matrix and vector formulations, in a fraction of the time. Programs written using MATLAB can be interfaced with programs written in other programming languages including C, C++, Java, and FORTRAN ## 3.2 MATLAB as a calculator - As an example of a simple interactive calculation, just type the following expression 1 + 2 × 3 at the prompt command \>\> and then press the Enter key to compute it. You obtain the following window: \>\>1 + 2*3 ans = 7 - Note that if you do not specify an output variable, MATLAB uses a default variable *ans*, short for answer, to store the results of the current computation. - The variable *ans* is overwritten, if there is more than one computation. It always stores the result of the last calculation, as one can see from Fig. 3.2 which shows simple calculations and displaying *ans* after the prompt command and pressing the Enter key. \>\>1 + 2*3 ans = 7 \>\>3 + 5 ans = 8 - To avoid this, you may assign a value to a variable as you see in Fig. 3.3. - Note from Fig. 3.3 that the variable *x* can always be used to refer to because it is stored in the computer memory in a location named *x*. Therefore, the expression *y = x,* assigns what is in the location *x* to another location in the memory designated by the variable named *y*. Both these two variables *x* and *y* can be used in a new expression *z = x + y*. All the values of variables *x, y, and z* are stored in computer memory locations named *x, y, and z* respectively, as in Fig. 3.4. \>\>x = 1+ 2*3 x = 7 \>\>y =x y = 7 \>\>z = x + y z = 14 ## 3.3 Guidelines for working in the Command Window - The command is executed once the Enter key is pressed. - Several commands can be typed in the same line but must be separated by a comma and they are executed in order from left to right. - Use the up arrow key (↑) to go back to a previously command line in the Command Window if you want to modify it and then re-execute it. - Use the down arrow key (↓) to move down to the previously typed command. - If a command is too long to fit in one line, type three dots ... to make it continue to the next line and then press the Enter key. ## 3.4 The semicolon symbol (;) - When a semicolon (;) is typed at the end of a command, the output of the command is not displayed when the Enter key is pressed. This is useful when the output is obvious or very large. - If several commands are typed in the same line, the output from any of the commands will not be displayed if a semicolon is typed between the commands instead of a comma. ## 3.5 The percent symbol (%) - When the symbol % is typed at the beginning of a line, the line is designated as a comment i.e., when the Enter key is pressed, the line is not executed. - Comments are used in programs to add description or to explain the program. Usually, there is no need for comments in the Command Window。 ## 3.6 The Percent-Brace %{ %} - The %{ and %} symbols enclose a block of comments that extend beyond one line. - Enclose any multiline comments (called block comment) with percent followed by an opening or closing brace as follows: \>\>%{ The purpose of this example is to compute y = f(x) %} - The %{ and %} operators must appear alone on the lines that immediately precede and follow the block of comments. Do not include any other text on these lines. ## 3.7 The clc command - Typing *clc* after the prompt (>>) and pressing the Enter key clears the Command Window. - The *clc* command does not change anything that was done before: if some variables were defined previously, they still exist and can be used. - You can use the up arrow key to recall commands that were typed before. ## 3.8 The arithmetic operations with numbers - Numbers can be assigned to variables, which can subsequently be used in calculation. - There are three kinds of numbers used in MATLAB: - Integers - Real numbers - Complex numbers - Integer numbers have no fractional part or decimal point. Integers are entered without the decimal point as follows: \>\> *xi* = 10 *xi* = 10 - Real numbers have fractional part or decimal point. They are entered with the decimal point as follows: \>\>*xr* = 10.0321 *xr* = 10.0321 - Complex numbers are constructed from real and imaginary components. The complex number *c = x+ yi* is represented in MATLAB as *c= complex (x, y)* where *x*, and *y* are the real and imaginary components respectively. The symbol *i* or *j* is the imaginary unit √-1. The following example illustrates the representation of a complex number in MATLAB and how to obtain the real and the imaginary component of a complex number using *real()*, and *imag()* respectively. \>\> *c* = complex (3, 4) *c* = 3.0000 + 4.0000i \>\> *x* = real (*c*) *x* = 3 \>\> *y* = imag (*c*) *y* = 4 - The six basic arithmetic operations with numbers used in MATLAB are presented in Table 3.2. - Table 3.3 presents the order of precedence of the arithmetic operations. | Operation | Symbol | Example | |--------------------|---------|---------------------------| | Addition | + | \>\> 6 + 2 | | | | *ans* = | | | | 8 | | Subtraction | - | \>\> 6 - 2 | | | | *ans* = | | | | 4 | | Multiplication | * | \>\> 6 * 2 | | | | *ans* = | | | | 12 | | Left division | / | \>\> 6 / 2 | | | | *ans* = | | | | 3 | | Right division | \ | \>\> 6 \ 2 | | | | *ans* = | | | | 0.3333 | | Exponentiation | ^ | \>\> 6^2 | | | | *ans* = | | | | 36 | | Precedence | Mathematical operation | |-------------|-------------------------------| | First | Parentheses | | | For nested parentheses, the innermost are executed first | | Second | Exponentiation | | Third | Multiplication and division both are equal precedence | | Fourth | Addition and subtraction | - In a mathematical expression that has several operations; higher precedence operations are executed before lower precedence operations. If two or more operations have the same precedence, the expression is executed from left to right. Parentheses are used to change the order of calculations. ### Examples The purpose of the following examples is to illustrate the order of precedence of the arithmetic operations in the calculation of mathematical expressions and some of the discussed commands and features. - \>\> 3 + 4/2 % 4/2 is executed first ans = 5 - \>\> (3 + 4)/2 % (3 + 4) is executed first ans = 3.5000 - \>\> 3 + 4/2 - 2 % 4/2 is executed first, then addition and subtraction \>\>%{ The following example calculate the expression 9^(1/2)+27^2/3 1½ is executed first, 9 ^ (1/2), then 27 ^ 2 and 27 ^ 2 / 3 are executed next and + is executed last. %} \>\> 9^(1/2) + 27^2/3 ans = 246 \>\>% Using the three periods ... to continue to the next line \>\>4*2 + (6+8)/4 + 4*2^2 + 2*3^2 - 2*52/63 +4 + 3/ (15 -8/2) ... + 6/3 % Leave a single space after (15 - 8/2), then type ... and press Enter ans = 50.1219 \>\>% the comma is used when we need to calculate more than one \>\>%expression in one line \>\>4/3 +5* 2 ,7-9 + 27/8 ans = 11.3333 ans = 1.3750 \>\>% The semicolon is used to prevent the calculation of the \>\>% expression in the command window. \>\>5*9 + 8^2; ## 3.9 Variables in MATLAB - The name of variable consists of a letter, followed by any number of letters, digits, or underscores. - The first character of the variable's name should not be a number. - The variable's name should not contain spaces. - MATLAB is case sensitive: it distinguishes between uppercase and lowercase letters, N and n are not the same variable. - The maximum number of characters of a variable's name in MATLAB R2009a is 63 characters. - To determine the maximum number of characters of a variable's name of the MATLAB version installed in your computer: type N = namelengthmax (namelengthmax is a built-in function) in the Command Window and press the Enter key as: \>\>N = namelengthmax N = 63 - The = sign in MATLAB is called the assignment operator. It takes the following form: Variable_name = A numerical value, or computable expression - The left hand side of the assignment operator can include only one variable name. - The right hand side of the assignment operator can be a number, or a computational expression that can include numbers and/or variables that were previously assigned numerical values. - When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of memory storage. If the variable already exists, MATLAB changes its contents. For example, num_students = 25 creates a variable named num_students and stores the value 25 in a memory location called num_students. - To view the value assigned to any variable, simply type the variable name and press the Enter key. MATLAB displays the variable name and its assigned value in the next two lines as \>\>num_students = 25 num_students = 25 \>\> - Avoid using the names of a built-in function (explained later) for a variable, because once a function name is used to define a variable, the function cannot be used. - The following are valid MATLAB variable assignments: a = 1 speed = 1500 BeamForm_Output_Type1 = y1\*Q\*y2 - These are invalid assignments: 2for1 = yes (Because the first character is a number) first one = 1 (Because the variable name contains a space) - There are a number of variables that are already defined when MATLAB is started. Some of these predefined variables are: - *ans* A variable that has the value of the last expression that was not assigned to a specific variable. - *pi* the number π, and equals 3.1416 - *inf* used for infinity ∞ - *eps* the smallest difference between two numbers, which equals to 2^(-52), it equals 2.2204e-016 - *i* defined as √-1 which is 0 + 10000i - *j* same as *i* - *NaN* stands for Not-a-Number. Used when MATLAB cannot determine a valid numeric value, as 0/0. - The following Command Window displays the values of the predefined variables \>\> pi ans = 3.1416 \>\> eps ans = 2.2204e-016 \>\> inf ans = Inf \>\> i ans = 0 + 1.0000i \>\> j ans = 0 + 1.0000i \>\> 0/0 ans = NaN ### Examples \>\>%{ Example1: assigns 8 to the variable *y* %} \>\> y = 8 y = 8 \>\>%{ Example 2: Assigns a new value to *y*. The new value is 5 times the previous value of *y* divided by 4 %} \>\> y = 5*y/4 y = 10 \>\>%{ Example 3: Assigns -6 to x, 3 to y and calculates the expression z = 3*x^2*y^2. A comma is used to separate between the assignment expressions to type them all in the same line %} \>\> x = -6, y = 3, z = 3 *x^2 * y^2 x = -6 y = 3 z = 972 \>\>%{ Example 4: The same as example 3, but it uses the semicolon (;) between x and y to only display the value of z %} \>\> x = -6; y = 3; z = 3 * x^2 * y^2 z = 972 ## 3.10 Commands for managing variables - When you define a variable at the MATLAB prompt, it is defined inside of MATLAB's "Workspace". - The Workspace is temporarily memory locations contain all the defined variables in the current MATLAB's session. - During a session of using MATLAB, one may use too many variables that cannot be remembered, and may be affect the computation of the next problem. Therefore, the use of one of the following commands is good for managing variables in the Workspace. - *who* Displays a list of variables currently in the Workspace. - *whos* Displays a list of variables currently in the Workspace and their sizes together with information about their bytes and class. - *clear* Removes all variables from the Workspace. - *clear x y z* Removes only variables x, y, and z. - Note that the command *clc* clears the screen and does not remove what are stored in the Workspace. ### Examples \>\> a =3 a = 3 \>\> b = 6 , x = a+ b/a % a comma is used to type more than one expression b = 6 x = 5 \>\> *who* % *who* command is used to display variables in memory Your variables are: abx \>\> *whos* % *whos* is used to display variables“ details Name Size Bytes Class Attributes a 1x1 8 double b 1x1 8 double x 1x1 8 double \>\> clear x % *clear* command removes the variable x from the memory \>\> *who* % *who* command display only the two variables a and b Your variables are: ab \>\> ## 3.11 Elementary math built-in functions - A function should have a name and accepts one or more MATLAB variables (called arguments) between parentheses as inputs, operates on them in some way, and then returns one or more MATLAB variables as outputs. - Table 3.4 lists some commonly used built-in functions, where variables x and y can be numbers, a variable that has been assigned a numerical value, or a computable expression. | Function | Description | Function | Description | |----------|-------------|------------|---------------------| | *cos(x)* | Cosine | *abs(x)* | Absolute value | | *sin(x)* | Sine | *sign(x)* | Signum function | | *tan(x)* | Tangent | *max(x)* | Maximum value | | *acos(x)* | Arc cosine | *min(x)* | Minimum value | | *asin(x)* | Arc sine | *ceil(x)* | Round towards +∞ | | *atan(x)* | Arc tangent | *floor(x)* | Round towards -∞ | | *exp(x)* | Exponential | *round(x)* | Round to nearest integer | | *sqrt(x)* | Square root | *rem(x,y)* | Remainder after division | | *log(x)* | Natural logarithm | *angle(x)* | Phase angle | | *log10(x)*| Common logarithm | *conj(x)* | Complex conjugate | ### Examples \>\>%Example1: Calculating the natural logarithm of 753 (In 753) \>\> log(753) ans = 6.6241 \>\>%Example2: Calculate y= 2\*sqrt(a\^2-c\^2), where a=5 and c= 4 \>\> a = 5 % assigning 5 to a a = 5 \>\> c = 4 % assigning 4 to c c = 4 \>\> y = 2\* sqrt(a\^2-c\^2) y = 6 \>\>%Example3: Example2 can be typed in a single line using the comma \>\> a=5, c=4, y = 2\*sqrt(a\^2-c\^2) a = 5 c = 4 y = 6 \>\> - Because MATLAB is a huge program; it is impossible to cover all the details of each function one by one. However, you can request information on a specific function by typing *help* followed by the function name in the Command Window, then pressing the Enter key as shown in the following example: % This example shows how to get information on the *sqrt* function \>\> help sqrt SQRT Square root. SQRT(X) is the square root of the elements of X. Complex results are produced if X is not positive. See also sqrtm, realsqrt, hypot. Overloaded methods: codistributed/sqrt sym/sqrt Reference page in Help browser doc sqrt ## 3.12 Display formats in MATLAB - The format in which MATLAB displays output on the screen can be changed by the user. The default output format is fixed point with four decimal digits (called short). - The format can be changed with the *format* command. - Once the *format* command is entered, all the output that follows will be displayed in the specified format. - Several of the available formats are listed and described in Table 3.5. | Command | Description | Example | |---------------|------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| | *format short* | Fixed point with four decimal digits for: 0.001 ≤ *number* ≤ 1000 <br>Otherwise display *format short e*. | \>\> 290/7 <br> *ans* = <br>41.4286 | | *format long* | Fixed point with 14 decimal digits for: 0.001 ≤ *number* ≤ 100 <br>Otherwise display *format long e*. | \>\> 290/7 <br> *ans* = <br>41.42857142857143 | | *format short e*| Scientific notation with four decimal digits. | \>\> 290/7 <br> *ans* = <br>4.1429e+001 | | *format long e*| Scientific notation with 15 decimal digits. | \>\> 290/7 <br> *ans* = <br>4.142857142857143e+001 | | *format short g*| Best of 5-digit fixed or floating point. | \>\> 290/7 <br> *ans* = <br>41.429 | | *format long g* | Best of 15-digit fixed or floating point. | \>\> 290/7 <br> *ans* = <br>41.4285714285714 | | *format bank* | Two decimal digits. | \>\> 290/7 <br> *ans* = <br>41.43 | ## 3.13 Matrices in MATLAB - MATLAB is an abbreviation for "MATrix LABoratory”. Therefore, the basic for data representation in MATLAB is a matrix. - A matrix is a two-dimensional rectangular array of real or complex numbers containing a certain number m of rows and a certain number of n columns. - The numbers m and n are the sizes of a matrix. - When m = 1, the matrix becomes a row vector with n elements. - When n = 1, the matrix is called a column vector with m elements. - When m = n = 1, the matrix contains one element which is called a scalar number. - Here are some diagrams showing, from left to right, a scalar, a column vector, a row vector, and a matrix: ``` 5 3 7 5 88 3 11 9 5 6 7 2 33 8 ``` - The scalar is 1 × 1, the column vector is 3 × 1 (3 rows by 1 column), the row vector is 1 × 4 (1 row by 4 columns), and the matrix is 3 × 3. All the values stored in these matrices are stored in what are called elements. ### 3.13-1 Creating a vector - Vector is created by assigning its elements to a variable. This can be done in several ways: - When a vector contains specific numbers that are known, the value of each element is entered directly by typing the values of the elements inside square brackets: variable_name = [number number ... number] - For a row vector, the numbers are typed with a space or a comma between the elements. For a column vector the numbers are typed with a semicolon between them. Each element can also be a mathematical expression that can include predefined variables, numbers, and functions. - When a vector contains a series of numbers with constant spacing. It can be created using colon operator by typing: variable_name = First : Step : Last - where First is the first element, Step is the spacing (increment or step value), and Last is the last element. - When a vector contains n values linearly spaced between the first element (First) and the last element (Last), including First and Last. This vector use the *linspace* function and has the form: variable_name = linspace (First, Last, n) ### Several examples of constructing vectors are: \>\> % Row vector by typing elements with space between. \>\> a= [1984 1986 1988 1990 1992 1994 1996] a = 1984 1986 1988 1990 1992 1994 1996 \>\> % Row vector by typing elements with comma between. \>\> a= [1984, 1986, 1988, 1990, 1992, 1994,1996] a = 1984 1986 1988 1990 1992 1994 1996 \>\> b = [2; 4; 10; 3 ] % Column vector by typing elements. b = 2 4 10 3 \>\> x = [1:2:14] % Row vector with constant spacing. x = 1 3 5 7 9 11 13 % Row vector with 6 elements, first element 0, last element 8. \>\> y = linspace (0, 8, 6) y = 0 1.6000 3.2000 4.8000 6.4000 8.0000 ### 3.13-2 Creating a two-dimensional array (matrix) - A two-dimensional array, also called a matrix, has numbers in rows and columns. A matrix is created by assigning the elements of the matrix to a variable. This is done by typing the elements, row by row, inside square brackets []. Within each row the elements are separated with spaces or commas. Between rows type; or the press Enter. variable_name= [1st row elements; 2nd row elements; ....; last row elements] - The elements that are entered can be numbers or mathematical expressions that may include numbers, predefined variables, and functions. - All the rows must have the same number of elements. If an element is zero, it has to be entered as such. MATLAB displays an error message if an attempt is made to define an incomplete matrix. Examples of matrices created in different ways are: \>\> a = [5 35 43; 476 81; 21 32 40] a = 5 35 43 4 76 81 21 32 40 \>\> cd = 6; e = 3; h = 4; \>\> Mat = [e, cd*h, cos(pi/3); h^2, sqrt(h*h/cd), 14] Mat = 3.0000 24.0000 0.5000 16.0000 1.6330 14.0000 \>\> b = [2:4; 3:5] b = 2 3 4 3 4 5 \>\> c = [ 2 6 88 33 5 2 ] c = 2 6 88 33 5 2 - All variables in MATLAB are arrays. A scalar is an array with one element: a vector is an array with one row, or one column, of elements: and a matrix is an array with elements in rows and columns. - The variable (scalar, vector, or matrix) is defined by the input when the variable is assigned. There is no need to define the size of the array (single element for a scalar, a row or a column of elements for a vector, or a two-dimensional array of elements for a matrix) before the elements are assigned. - Once a variable exists as a scalar, a vector, or a matrix, it can be changed to be any other size, or type, of variable. For example, a scalar can be changed to a vector or a matrix, a vector can be changed to a scalar, a vector of different length, or a matrix, and a matrix can be changed to have a different size, or to be reduced to a vector or a scalar. These changes are made by adding or deleting elements. ### 3.13-3 Array addressing (Referring to and Modifying Matrix Elements) - To refer to matrix elements, the row and then the column indices are given in parentheses (always the row index first and then the column). ### Examples \>\> mat = [2:4; 3:5] mat = 2 3 4 3 4 5 \>\> mat(2,3) ans = 5 \>\> VCT = [35 46 78 23 5 14 81 3 55] VCT = 35 46 78 23 5 14 81 3 55 \>\> VCT(4)=-2; VCT(6) = 273 VCT = 35 46 78 -2 5 273 81 3 55 \>\> VCT(5)^VCT(8)+sqrt(VCT(7)) ans = 134 \>\> MAT = [3 11 6 5; 4 7 10 2;13 9 0 8] MAT = 3 11 6 5 4 7 10 2 13 9 0 8 \>\> MAT(3,1) = 20 MAT = 3 11 6 5 4 7 10 2 20 9 0 8 \>\> MAT (2,4) -MAT(1,2) ans = -9 - A colon (:) can be used to address a range of elements in a vector or a matrix. If v is a vector, v(m:n) refers to elements m through n of the vector v. - If A is a matrix, A(:,n) refers to the elements in all the rows of column n. A(n,:) refers to the elements in all the columns of row n. A(:,m:n) refers to the elements in all the rows between columns m and n. A(m:n,:) refers to the elements in all the columns between rows m and n. A(m:n,p:q) refers to the elements in rows m through n and columns p through q. \>\> v = [4 15 8 12 34 2 50 23 11 ] v = 4 15 8 12 34 2 50 23 11 \>\> u = v(3:7) u = 8 12 34 2 50 \>\> A = [ 1 3 5 7 9 11; 2 4 6 8 10 12; 3 6 9 12 15 18; 4 8 12 16 20 24; 5 10 15 20 25 30] A = 1 3 5 7 9 11 2 4 6 8 10 12 3 6 9 12 15 18 4 8 12 16 20 24 5 10 15 20 25 30 C = A(2,:) C = 2 4 6 8 10 12 \>\> F = A (1:3,2:4) F = 3 5 7 4 6 9 12 6 - All variables in MATLAB are arrays. A scalar is an array with one element: a vector is an array with one row, or one column, of elements: and a matrix is an array with elements in rows and columns. - The variable (scalar, vector, or matrix) is defined by the input when the variable is assigned. There is no need to define the size of the array (single element for a scalar, a row or a column of elements for a vector, or a two-dimensional array of elements for a matrix) before the elements are assigned. - Once a variable exists as a scalar, a vector, or a matrix, it can be changed to be any other size, or type, of variable. For example, a scalar can be changed to a vector or a matrix, a vector can be changed to a scalar, a vector of different length, or a matrix, and a matrix can be changed to have a different size, or to be reduced to a vector or a scalar. These changes are made by adding or deleting elements. ### 3.13-3 Array addressing (Referring to and Modifying Matrix Elements) - To refer to matrix elements, the row and then the column indices are given in parentheses (always the row index first and then the column). ## 3.13-4 Addition and subtraction of matrices \>\>VA=[8 5 4]; VB = [10 2 7] \>\>VC=VA + VB VC= 18 7 11 \>\>A=[5 -3 8; 9 2 10], B= [10 7 4; -11 15 1] A = 5 -3 8 9 2 10 B = 10 7 4 -11 15 1 \>\> C = A + B C = 15 4 12 -2 17 11 \>\>C-8 ans = 7 -4 4 9 -6 3 ## 3.13-5 Multiplication and exponentiation of matrices - MATLAB allows arithmetic multiplication (*) and exponentiation (^) to be carried out on matrices. The multiplication operation is executed by MATLAB according to the rules of linear algebra. This means that if A and B are two matrices, the operation A* B can be carried out only if the number of columns in matrix A is 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 E is a (3 x 2) matrix and G is a (2 x 4) matrix, then the operation C=A\*B gives a (3 x 4) matrix: \>\>A=[2 -1; 8 3; 6 7], B=[4 9 1 -3; -5 2 4 6] A= 2 -1 8 3 6 7 B = 4 9 1 -3 -5 2 4 6 \>\> C = A*B C= 13 16 -2 -12 17 78 20 -6 -11 68 34 24 - If & only if n1 =