Introduction to MATLAB PDF
Document Details

Uploaded by WellEstablishedEternity9841
Dr Lim
Tags
Summary
This document is an introduction to MATLAB, a mathematical and graphical software package. It covers topics such as variables, assignment statements, colon operators, linspace functions, creating matrix variables, numerical expressions, and relational expressions. MATLAB is used in fields like engineering, science, finance, and economics.
Full Transcript
Introduction to MATLAB Engineering Computing INTRODUCTION What is MATLAB? MATLAB is a mathematical and graphical software package. Everything in MATLAB is written to work with vectors and matrices. It is a package with numerical, graphical, a...
Introduction to MATLAB Engineering Computing INTRODUCTION What is MATLAB? MATLAB is a mathematical and graphical software package. Everything in MATLAB is written to work with vectors and matrices. It is a package with numerical, graphical, and programming capabilities. It has built-in functions to perform many operations, and there are toolboxes that can be added to augment these functions. It is used generally in fields such as engineering, science, finance and economics. It can perform calculations (as with a calculator), plotting (develop graphical illustration) as well as implement algorithm. Getting into MATLAB The central screen is called the Command Window. Work will mostly be done here. In the Command Window, the following can be seen: >> or > It is called the prompt. In the Command Window, MATLAB can be used interactively. At the prompt, any MATLAB command or expression can be entered, and MATLAB will respond immediately with the result. It is also possible to write programs in MATLAB that are contained in script files or M-files. MATLAB Desktop environments Available variables can be seen in the Workspace. Folders and script files can be seen in the Current Folder. Dr Lim (based on Hasnanizan bte Taib’s notes) 1 Introduction to MATLAB Engineering Computing Getting Help Some useful commands - they must be written in lower case – can be tried out as a beginner are: demo, will bring up MATLAB examples in the Help Browser, which has examples of some of the features of MATLAB. help, will explain any function; help help will explain how help works. lookfor is used to search through the help for a specific word or phrase (note: this can take a long time). doc is used to bring up a documentation page in the Help Browser (replaced by Internet Browser). Exiting MATLAB To exit from MATLAB, either type quit or type exit at the prompt, or just close the program. COMMANDS Variables and Assignment Statements To store a value in a MATLAB session, or in a program, a variable is used. The Workspace Window shows variables that have been created and their values. Putting the first or initial value in a variable is called initializing the variable. One easy way to create a variable is to use an assignment statement. The format of an assignment statement is variablename = expression, for example x = 2. The variable is always on the left, followed by the = symbol, which is the assignment operator (unlike in mathematics, the single equal sign does not mean equality), followed by an expression. The presence of spaces adjacent to the equal sign is optional. The expression is evaluated and then that value is stored in the variable. MATLAB uses a default variable named ‘ans’ if an expression is typed at the prompt and it is not assigned to a variable say, typing 3+4, gets ans = 7. A shortcut for retyping commands is to hit the up arrow, which will go back to the previously typed command(s). Say combine the variablename result with the previous command: result = 3+4. There are 3 basic types of numbers that will be used: Scalars (i.e. a plain number); Vectors (i.e. a list of numbers); and Matrices (i.e. a tables of numbers). All these variables are represented as matrices. If x = 5 is typed in, followed by size(x), MATLAB reports it is a 1 by 1 matrix Creating Row Vectors There are several ways to create row vector variables. The most direct way is to put the values that wanted in the vector in square brackets, separated by either spaces or commas. If y = [1,2,3] or y = [1 2 3], it will create a vector with elements 1, 2 and 3. Then typing size(y), MATLAB will report it is a 1 by 3 vector or a 1 by 3 matrix. If y = [1 2 3 ]; is typed in, ie. with the semicolon, it will supress the printout of the value of y. Dr Lim (based on Hasnanizan bte Taib’s notes) 2 Introduction to MATLAB Engineering Computing The Colon Operator and Linspace Function If, as in the previous examples, the values in the vector are regularly spaced, the colon operator : can be used to iterate through these values. For example, 1:5 results in all of the integers from 1 to 5 inclusive, for example vec = 1:5. Note that, in this case, the brackets [ ] are not necessary to define the vector, as it is merely a row vector. With the colon operator, a step value can also be specified by using another colon, in the form (first:step:last). For example, to create a vector with all integers from 1 to 9 in steps of 2, use nv = 1:2:9 Note that this is called incrementing. Try creating a vector with all integers of decrementing values? The linspace function creates a linearly spaced vector. linspace(x,y,n) creates a vector with n values in the inclusive range from x to y. If n is omitted, the default is 100 points. For example, the following creates a vector with five values linearly spaced between 3 and 15, including the 3 and 15: ls = linspace(3,15,5) Similarly, the logspace function creates a logarithmically spaced vector. logspace(x,y,n) creates a vector with n values in the inclusive range from 10^x to 10^y. If n is omitted, the default is 50 points. For example, logspace(1,5,5) Vector variables can also be created using existing variables. (creating vector variables using existing variables / concatenating the vectors) For example, a new vector is created here consisting, first of all, of the values from nv (from above example) followed by all values from ls (from another above example): newvec = [nv ls] Creating Matrix Variables Create a matrix is similar to creating a vector. There is just a need to separate each row. That is done with a semicolon. A = [ 1 2; 3 4] is a 2 by 2 matrix with elements 1, 2, 3 and 4. When working with vectors and matrices and multiplication and so on, the dimensions of the vectors/matrices are very important. Typically, column vectors are used in calculations, not row vectors, such as what was just created. Iterators can be used for the values in the rows using the colon operator. For example, mat = [2:4; 3:5] The separate rows in a matrix can also be specified by hitting the Enter key after each row instead of typing a semicolon when entering the matrix values, as in newmat = [2 6 88 33 5 2] Matrices of random numbers can be created using the rand function. If a single value n is passed to rand, an n x n matrix will be created, or passing two arguments will specify the number of rows and columns. Examples include rand(2) and rand(1,3). Matrices of random integers can be generated using the randi function; after the range is passed, the dimensions of the matrix are passed (again, using one value n for an n x n matrix, or two values for the dimensions). Examples are randi([5, 10], 2) and randi([10, 30], 2, 3). Note that the range can be specified for the randi function, but not for rand function. The format for calling these functions is different. Dr Lim (based on Hasnanizan bte Taib’s notes) 3 Introduction to MATLAB Engineering Computing Creating Column Vectors The previous vector y can be transposed, i,e from a row vector into a column vector by using the apostrophe operator, y = y’. With the size(y) function, it can be seen that it is a column vector now. Note that it can also be initialised by typing using semicolons, for example y = [1;2;3]. Referring to and Modifying Elements The element(s) within a matrix can be accessed. For example if the element in matrix A’s ith row and jth column is require, the A(i,j) operator can be used. For example, using A(1,1), A(2,1) and so on. Another interesting thing to do is access a vector within a matrix. Say the first row of Matrix A is required, the colon syntax can be used to get all the elements is row one. The command is A(1,:) will produce elements 1 and 2, ie. all the elements in Row 1. If the entire second column is wanted, A(:,2) will give me 2 4 all elements in column 2. For A(:,:), all elements of Matrix A will be called. For a vector, only one position is required. For example, for V=2:2:10, V(3) will call the third element in the list. An individual element in a matrix can be modified by assigning a new value to it. For example, for mat = [2:4; 3:5]; mat(1,2) = 11. An entire row or column can also be changed. For example, the following replaces the entire second row with values from a vector obtained using the colon operator. mat(2,:) = 5:7 Notice that as the entire row is being modified, a row vector with the correct length must be assigned. Any subset of a matrix can be modified as long as what is being assigned has the same number of rows and columns as the subset being modified. To extend a matrix an individual element cannot be added as that will mean there will no longer be the same number of values in every row. However, an entire row or column can be added. For example, the following will add a fourth column to the matrix: mat(:,4) = [9 2]' If there is a gap between the current matrix and the row or column being added, MATLAB will fill in with zeros. mat(4,:) = 2:2:8 Let’s create a bigger matrix now to better illustrate the next point. For example, A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] is a 4 by 4 matrix. The current syntax can also be used to access ranges. If the middle four elements are required, then the operator A(2:3, 2:3) can be used. A(1,1) will return the first element, but not A (0,0). Calling syntax can be used all by itself because it creates ranges. For 1:10, all numbers from 1 to 10 are produced. Let’s assign this to a variable. Use up arrow to go to a previous command and add W at the front to get W = 1:10. Then check the size of W using size(W). This is simpler to do than typing manually [1 2 3 4 5 6 7 8 9 10]. Dr Lim (based on Hasnanizan bte Taib’s notes) 4 Introduction to MATLAB Engineering Computing MATLAB is not limited to only scalars, vectors and matrices. Data structures called tensor, are multi- dimensional matrices. It is not merely a table of matrix, but more like a cube or hypercube. Instead of having a 2 by 2 matrix, it can be a 2 by 2 by 2 tensors. Numerical Expressions Expressions can be created using values, variables that have already been created, operators, built-in functions and parentheses. For numbers however, these can include operators such as multiplication and functions such as trigonometric functions. Now let’s go thru some basic arithmetic in MATLAB. That is the usual operation: Addition, subtraction, multiplication and division, and the use of parentheses. First let’s create some matrices: A=[1 2; 3 4]; B=[5 6; 7 8]; C=[9 10; 11 12]. For addition, the command can be A+B, for subtraction, A-B. For multiplication, A*B. Note that the Inner dimensions of A and B have to be the same. Let’s create another matrix B2 which does not have the same number of rows as the number of columns of A. Say B2 = [1 2; 4 5; 6 7]. Check size(B2) and size(A). A*B produces as 2 by 2 matrix. A*B2 will produce an error message while A*B2’ will produce a 2 by 3 matrix. Matrix division such as A/B is possible. There is also backward division which is used later in systems of linear equations. Two numbers can be divided using the forward or backward slash, for example, 1/3 or 1\3, but they have different results. 1/3 is 1 divided by 3, while 1\3 is 3 divided by 1. The Operator Precedence Rules has anything to do with parenthesis comes first then, followed by multiplication/division, followed by addition and subtraction. Types of Operators There are, in general, two types of operators: unary operators, which operate on a single value, or operand, and binary operators, which operate on two values or operands. The symbol ‘-‘, for example, is both the unary operator for negation and the binary operator for subtraction. Here are some of the common operators that can be used with numerical expressions: + addition, - negation or subtraction, * multiplication, / division and ^ exponentiation. Nested parentheses are parentheses inside of other parentheses; the expression in the inner parentheses is evaluated first. For example, in the expression 5-(6*(4+2)), the addition is performed first followed by the multiplication, and finally, the subtraction, to result in -31. Relational Expressions Expressions that are conceptually either true or false are called relational expressions. They are also sometimes called Boolean expressions or logical expressions. These expressions can use both relational operators (which relate two expressions of compatible types) and logical operators (which operate on logical operands). The relational operators in MATLAB are: Dr Lim (based on Hasnanizan bte Taib’s notes) 5 Introduction to MATLAB Engineering Computing > greater than < less than >= greater than or equals 9 will produce logical results, not double precision results. MATLAB also has built-in true and false. In other words, true is equivalent to logical(1) and false is equivalent to logical(0). Although these are logical values, mathematical operations can be performed on the resulting 1 or 0. The result of 5 < 7, can be used for subsequent addition, such as ans + 3. The logical operators are: || or && and ~ not All logical operators operate on logical or Boolean operands. The not (i.e. ~) operator is a unary operator; the others are binary. The not operator will take a logical expression, either true or false, and give the opposite value. For example, ~(3 < 5) is false as (3 < 5) is true. The or (i.e. ||) operator has two logical expressions as operands. The result is true if either or both of the operands are true, and false only if both operands are false. The and (i.e. &&) operator also operates on two logical operands. The result of an and expression is true only if both operands are true; it is false if either or both are false. The or/and operators shown here are used for scalars or single values. The || and && operators in MATLAB are examples of operators that are known as short-circuit operators. What this means is that if the result of the expression can be determined based on the first part, then the second part will not even be evaluated. For example, in the expression: 2 < 4 || 'a' == 'c' the first part, 2 < 4, is true so the entire expression is true; the second part 'a'== 'c' will not be evaluated. In addition to these logical operators, MATLAB also has a function xor, which is the exclusive or function. It returns logical true if one (and only one) of the arguments is true. For example, in the following only the first argument is true, so the result is true: xor(3 < 5, 'a' > 'c'). Dr Lim (based on Hasnanizan bte Taib’s notes) 6 Introduction to MATLAB Engineering Computing In this example, both arguments are true so the result is false: xor(3 < 5, 'a' < 'c'). Given the logical values of true and false in variables x and y, the following truth table shows how the logical operators work for all combinations. Note that the logical operators are commutative (e.g. x || y is the same as y || x). As with the numerical operators, it is important to know the operator precedence rules. For the operators that have been covered thus far, the following is the precedence (from the highest to the lowest): ( ) parentheses, ^ exponentiation, – negation, *, /, \ all multiplication and division, +, - addition and subtraction, =, ==, ~= relational, &&, xor, || logical, and assignment. Dr Lim (based on Hasnanizan bte Taib’s notes) 7