MATLAB Inroduction-Matrices2

Add to Favourites
Post to:
Comments
Presentation Transcript Presentation Transcript

Matrices and ProgrammingThesis123 : Matrices and ProgrammingThesis123 1

Slide 2 : ARRAYS (VECTORS) 2

COMMENTS,PUNCTUATION AND ABORTING EXECUTION : COMMENTS,PUNCTUATION AND ABORTING EXECUTION >>N=10 % NUMBER STUDENTS IN THE CLASS >>N=10; %SUPRESSION OF N (; Semicolon) >>N=10+13+17+36 …%continuation of the line 11+35; >>Ctrl+C %Interrupting the program 3

Matrices : Matrices Entering and Generating Matrices Subscripts Scalar Expansion Concatenation Deleting Rows and Columns Array Extraction Matrix and Array Multiplication 4

Slide 5 : a=[1 2;3 4] a = 1 2 3 4 b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = -2.8000 0 + 2.6458i 10.5000 b(2,5) = 23 b = -2.8000 0 + 2.6458i 10.5000 0 0 0 0 0 0 23.0000 Any MATLAB expression can be entered as a matrix element (internally, it is regarded as such) In MATLAB, the arrays are always rectangular Entering Numeric Arrays NOTE: 1) Row separator semicolon (;) 2) Column separator space OR comma (,) Use square brackets [ ] 5

Slide 6 : The Matrix in MATLAB 4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 23 83 13 0 10 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 A = Rectangular Matrix: Scalar: 1-by-1 array Vector: m-by-1 array 1-by-n array Matrix: m-by-n array 6

Slide 7 : w=[1 2;3 4] + 5 w = 6 7 8 9 x = 1:5 x = 1 2 3 4 5 y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 z = rand(2,4) z = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185 Scalar expansion Creating sequences: colon operator (:) Utility functions for creating matrices. Entering Numeric Arrays 7

Slide 8 : Numerical Array Concatenation a=[1 2;3 4] a = 1 2 3 4 cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24 Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] Note:The resulting matrix must be rectangular 4*a How to Concatenation matrices to build a large matrix: B = [A A A]; C=[B B;B B]; 8

N – Dimensional Matrices : A = [1 2 4 5 B = [5 3 7 9 6 3 8 2] 1 9 9 8] Multidimensional matrices can be created by concatenating 2-D matrices together The cat function concatenates matrices of compatible dimensions together: Usage: cat(dimensions, Matrix1, Matrix2) N – Dimensional Matrices 9

N – Dimensional Matrices : Examples A = [1 2 4 5 B = [5 3 7 9 6 3 8 2] 1 9 9 8] >> C = cat(3,[1,2,4,5;6,3,8,2],[5,3,7,9;1,9,9,8]) >> C = cat(3,A,B) >> X=cat(2,A,B) % X=[A,B]; >>Y=cat(1,A,B) %Y=[A;B]; N – Dimensional Matrices 10

Slide 11 : Deleting Rows and Columns A=[1 5 9;4 3 2.5; 0.1 10 3i+1] A = 1.0000 5.0000 9.0000 4.0000 3.0000 2.5000 0.1000 10.0000 1.0000+3.0000i A(:,2)=[] A = 1.0000 9.0000 4.0000 2.5000 0.1000 1.0000 + 3.0000i A(2,2)=[] ??? Indexed empty matrix assignment is not allowed. How to delete a row of a matrix: B(:,2) = [ ]; Delete 2nd column B(3,:) = [ ]; Delete 3rd row 11

Slide 12 : Array Subscripting / Indexing 4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 23 83 13 0 10 1 2 3 4 5 1 2 3 4 5 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) A(1:end,end) A(:,end) A(21:end)’ 12

Brackets : Brackets >> [1 2 3 5] % a row vector (actually, a 1x4 matrix) ans = 1 2 3 5 >> [1, 2, 3, 5] % a row vector using commas ans = 1 2 3 5 >> [1; 2; ] % a column vector (actually, a 2x1 matrix) ans = 1 2 >> [1 2 3 4; 2 4 6 8; 3 6 9 12] % a 3x4 matrix using semicolons ans = 1 2 3 4 2 4 6 8 3 6 9 12 >> [1 2 3 4 % a 3x4 matrix using Enter 2 4 6 8 3 6 9 12] ans = 1 2 3 4 2 4 6 8 3 6 9 12 >> 3 % a scalar (actually, a 1x1 matrix)ans = 3 13

A few things to note : A few things to note As you can see, everything in Matlab is treated as a matrix, including scalars. This is useful to keep in the back of your mind as you use the product. When calling any of these functions with one or more arguments, you may either call them in the form f(a, b, c), or you may give a single row vector, for example, f([a b c]). With a number of constructors, if only one dimension is provided, it is assumed you want a square matrix with that dimension. For example, ones(3) generates a 3x3 matrix of ones, whereas ones(3,2) generates a 3x2 matrix of ones. 14

Slide 15 : Brackets with Matrices All the examples above have scalar entries. It is also possible to have matrix entries: >> A = [1 2; 3 4]; [A [5; 6]] ans = 1 2 5 3 4 6 In this case, all matrices in the same row must have the same column dimension, and all matrices in the same column must have the same row dimension. Unfortunately, this is one place where scalars are not expanded. For example, to append a column of ones, you must do the following: >> [A 1]??? Error using ==> horzcatAll matrices on a row in the bracketed expression must have the same number of rows. >> [A ones(size(A,1), 1)] % [A ones(2,1)] works as well ans = 1 2 1 3 4 1 Notes: ones(2, 1) creates a 2×1 matrix of 1s. size( A, 1 ) returns the number of rows of A and size( A, 2 ) returns the number of columns of A. 15

Colon Operator : Colon Operator The colon operator x:y generates a row vector (1xn matrix) of the form [x, x+1, x+2, ..., x+n] where x+n <= y and x+n+1 > y. >> 3:7 ans = 3 4 5 6 7 >> 1.2:7.3 ans = 1.2000 2.2000 3.2000 4.2000 5.2000 6.2000 7.2000 The three variable form x:dx:z generates row vector [x, x+dx, x+2*dx, ..., x+n*dx] where x+n*dx <= y and x+(n+1)*dx > y. >> 3:2:11 ans = 3 5 7 9 11 >> 1.2:1.25:7.3 ans = 1.2000 2.4500 3.7000 4.9500 6.2000 The colon operator can be used in conjunction with brackets: >> [1:3 5 7:10] ans = 1 2 3 5 7 8 9 10 16

General Constructors : General Constructors 17

Slide 18 : diag The diag(v) function returns a matrix with specified diagonal entries. >> diag([1 2 3 4]) ans = 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 The diag(v, n) shifts the diagonal either to the right (positive n) or down (negative n.) diag(v, 0) is equivalent to diag(v). >> diag([1 2 3], 2) ans = 0 0 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 >> diag([1 2 3], -2) ans = 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 An alternate use of the diag function is to return the diagonal of a matrix. 18

eye : eye Build an Identity matrix: A= eye(n); Short for identity, eye returns an identity matrix. >> eye(3) ans = 1 0 0 0 1 0 0 0 1 >> eye(3,4) ans = 1 0 0 0 1 0 0 0 1 19

linspace : linspace The linspace(x, y, N) function generates a row vector with N linearly spaced points between x and y. >> linspace(3, 7, 10) % 10 linearly spaced points between 3 and 7 ans = 3.0000 3.4444 3.8889 4.3333 4.7778 5.2222 5.6667 6.1111 6.5556 7.0000 Note: The function linspace(x, y, N) is equivalent to x:(y-x)/(N-1):y. 20

LOGSPACE : LOGSPACE LOGSPACE Logarithmically spaced vector LOGSPACE(X1, X2) generates a row vector of 50 logarithmically equally spaced points between decades 10^X1 and 10^X2. If X2 is pi, then the points are between 10^X1 and pi. LOGSPACE(X1, X2, N) generates N points. For N < 2, LOGSPACE returns 10^X2. Class support for inputs X1,X2: float: double, single 21

ones : ones Build a one filled matrices: A= ones(n); is an n-by-n matrix of ones. A= ones(n,m); is an n-by-m matrix of ones. 22

rand : rand Uniformly distributed random numbers rand, randn, sprand, sprandn, randperm 23

zeros : zeros Build a zero filled matrices: A= zeros(n); is an n-by-n matrix of zeros. A= zeros(n,m); is an n-by-m matrix of zeros. 24

Slide 25 : Matrix operations The following table gives a list of all arithmetic operators which work on matrices. They are divided into three categories: The only new operator you are likely to see is the backslash or right divided operator. The expression a/b is equivalent to the operator b\a in Matlab. 25

Slide 26 : Simply Add(+), Subtract(-), Multiply(*), and Division(/) arrays and scalars. For A/S/M/D of an array by a scalar: B=A+2; B=A-2; B=A*2; B=A/2; Power n of a scalar: C=2; A=C^2; B=C^1.3; 26

Slide 27 : 27

Slide 28 : 28

Element-wise Operations : Element-wise Operations 29

Basic Matrix Functions : Basic Matrix Functions Matrix Dimensions Sorts, Sums, and Products Basic Linear Algebra Functions 30

Matrix Dimensions : Matrix Dimensions 31

Sorts, Sums, and Products : Sorts, Sums, and Products 32

Slide 33 : 33

Basic Linear Algebra Functions : Basic Linear Algebra Functions 34

Slide 35 : 35

Slide 36 : 36

Slide 37 : 37

Programming -I : Programming -I 38

Relational Operators : Relational operators are used to compare two scaler values or matrices of equal dimensions Relational Operators < less than <= less than or equal to > Greater than >= Greater than or equal to == equal ~= not equal Relational Operators 39

Relational Operators : Comparison occurs between pairs of corresponding elements A 1 or 0 is returned for each comparison indicating TRUE or FALSE Matrix dimensions must be equal! >> 5 == 5 Ans 1 >> 20 >= 15 Ans 1 Relational Operators 40

Relational Operators : A = [1 2 4 5 B = 7 C = [2 2 2 2 6 3 8 2] 2 2 2 2] Try: >>A > B >> A < C Relational Operators 41

Relational Operators : The Find Function The ‘find’ function is extremely helpful with relational operators for finding all matrix elements that fit some criteria A = [1 2 4 5 B = 7 C = [2 2 2 2 D = [0 2 0 5 0 2] 6 3 8 2] 2 2 2 2] The positions of all elements that fit the given criteria are returned >> find(D > 0) The resultant positions can be used as indexes to change these elements >> D(find(D>0)) = 10 D = [10 2 10 5 10 2] Relational Operators 42

Relational Operators : The ‘Find’ Function A = [1 2 4 5 B = 7 C = [2 2 2 2 D = [0 2 0 5 0 2] 6 3 8 2] 2 2 2 2] The ‘find’ function can also return the row and column indexes of of matching elements by specifying row and column arguments >> [x,y] = find(A == 5) The matching elements will be indexed by (x1,y1), (x2,y2), … >> A(x,y) = 10 A = [ 1 2 4 10 6 3 8 2 ] Relational Operators 43

Slide 44 : 44

Slide 45 : 45

Slide 46 : 46

Slide 47 : Relational operators are used as arithmetic operators within a mathematic expression. The result can be used in other mathematical operations, in addressing arrays, and together with other MATLAB commands (e.g. if) to control the flow of a program. When two numbers are compared, the result is 1 (logical true) if the comparison, according to the relational operator, is true, and 0 (logical false) if the comparison is false. 47

Slide 48 : If two scalars are compared, the result is a scalar 1 or 0. If two arrays are compared (only arrays with the same size can be compared), the comparison is done element-by-element, and the result is a logical array of the same size With 1’s and 0’s according to the outcome of the comparison at each address. If a scalar is compared with an array, the scalar is compared with every element of the array, and the result is a logical array with l’s and 0’s according to the outcome of the comparison of each element. 48

Slide 49 : 49

Slide 50 : The results of a relational operation with vectors, which are vectors with 0’s and 1’s, are called logical vectors and can be used for addressing vectors. When a logical vector is used for addressing another vector, it extracts from that vector the elements in the positions where the logical vector has 1’s. For example: 50

Slide 51 : Numerical vectors and arrays with the numbers 0’s and l’s are not the same as logical vectors and arrays with 0’s and l’s. Numerical vectors and arrays can not be used for addressing. Logical vectors and arrays, however, can be used in arithmetic operations. The first time a logical vector or an array is used in arithmetic operations it is changed to a numerical vector or array. Order of precedence: In a mathematical expression that includes relational and arithmetic operations, the arithmetic operations (+, -, *, /,\) have precedence over relational operations. The relational operators themselves have equal precedence and are evaluated from left to right. Parentheses can be used to alter the order of precedence. 51

Logical Operators : Logical Operators 52

Slide 53 : Logical operators have numbers as operands. A nonzero number is true, and a zero number is false. Logical operators (like relational operators) are used as arithmetic operators within a mathematical expression. The result can be used in other mathematical operations, in addressing arrays, and together with other MATLAB commands (e.g. if) to control the flow of a program. Logical operators (like relational operators) can be used with scalars and arrays. 53

Slide 54 : The logical operations AND and OR can have both operands as scalars, arrays, or one array and one a scalar. If both are scalars, the result is a scalar 0 or 1. If both are arrays they must be of the same size and the logical operation is done element-by-element. The result is an array of the same size with l’s and 0’s according to the outcome of the operation at each position. If one operand is a scalar and the other is an array, the logical operation is done between the scalar and each of the elements in the array and the outcome is an array of the same size with l’s and 0’s. The logical operation NOT has one operand. When it is used with a scalar the Outcome is a scalar 0 or 1. When it is used with an array, the outcome is an array of the same size with l’s in positions where the array has nonzero numbers and 0’s in positions where the array has zeros. The following are some examples: 54

Slide 55 : 55

Slide 56 : Relational operators are used as arithmetic operators within a mathematic expression. The result can be used in other mathematical operations, in addressing arrays, and together with other MATLAB commands (e.g. if) to control the flow of a program. When two numbers are compared, the result is 1 (logical true) if the comparison, according to the relational operator, is true, and 0 (logical false) if the comparison is false. 56

Useful Commands : Useful Commands 57

Slide 58 : 58

Slide 59 : 59

Special Matrices : Special Matrices 60

Slide 61 : zeros matrix of zeros ones matrix of ones eye identity diag diagonal toeplitz Toeplitz magic magic square compan companion linspace linearly spaced vectors logspace logarithmically spaced vectors meshgrid array for 3-D plots rand uniformly distributed random numbers 61

Slide 62 : randn normally distributed randon numbers hilb Hilbert invhilb inverse Hilbert (exact) vander Vandermonde pascal Pascal hadamard Hadamard hankel Hankel rosser symmetric eigenvalue test matrix Wilkinson Wilkinson's eigenvalue test matrix gallery two small test matrices 62

Matrix Manipulation : Matrix Manipulation 63

Slide 64 : diag create or extract diagonals rot90 rotate matrix 90 degrees fliplr flip matrix left-to-right flipud flip matrix up-to-down reshape change size tril lower triangular part triu upper triangular part .' transpose : convert matrix to single column; A(:) 64

Slide 65 : m files / scripts 65

Slide 66 : The editor / debugger 66

NOTES ABOUT SCRIPT FILES : NOTES ABOUT SCRIPT FILES A script file is a sequence of MATLAB commands, also called a program. • When a script file runs, MATLAB executes the commands in the order they are written just as if they were typed in the Command Window. • When a script file has a command that generates an output (e.g. assignment of a value to a variable without semicolon at the end), the output is displayed in the Command Window. • Using a script file is convenient because it can be edited (corrected and/or changed) and executed many times. • Script files can be typed and edited in any text editor and then pasted into the MATLAB editor. 67

Slide 68 : The RUN icon Definition of program Comments 68

: Creating and saving script files From file newM-file From file Save or Save as Running a script file Current directory Search path Using RUN icon in Editor file Using F5 Debug Run F5 In Command window >> type file name and enter 69

Global Variables : Global Variables Global variables are variables that, once created in one part of MATLAB, are recognized in other parts of MATLAB. This is the case for variables in the Command Window and script files since both operate on variables in the workspace. When a variable is defined in the Command Window, it is also recognized and can be used in a script file. In the same way, if a variable is defined in a script file it is also recognized and can be used in the Command Window. In other words, once the variable is created, it exists, can be used, and can be reassigned a new value in both the Command Window and a script file. 70

Input to a script file : Input to a script file The variable is defined and assigned value in the script file In script file Day1=30; Day2=20; Day3=50; ave=(Day1+Day2+Day3)/3; 71

Slide 72 : The variable is defined and assigned value in the command window >>Day1=30; >>Day2=20; >>Day3=50; Then run the script file ave=(Day1+Day2+Day3)/3; 72

Slide 73 : The variable s defined in the script file but a specific value is entered in the command window when the script file executed Var_name=input(‘string with a message that is displayed in the command window’) Ex: in script file Day1=input(‘Enter the value of Day1=’); Day2=input(‘Enter the value of Day2=’); Day3=input(‘Enter the value of Day3=’) %without semi... ave=(Day1+Day2+Day3)/3; 73

Other ways of using input command : Other ways of using input command Var_name is taken as charecter Used for options Var_name=input(‘string with a message that is displayed in the command window’,’s’) name=input(‘continue yes/no’,’s’) switch name case ‘yes’ exaple1 ………… 74

Output Command : Output Command The disp command disp(name of the variable) or disp(‘text as a string’) Displays output on Commnd window Ex: xyz=[1 2 3;3 2 4]; disp(xyz) disp(‘Hellow’) Note: only one variable can be displayed and if you want to use more …one after the other can be displayed. 75

Slide 76 : disp(‘ A B C’) disp(rand(3,3)) 0.0153 0.9318 0.8462 0.7468 0.4660 0.5252 0.4451 0.4186 0.2026 76

Slide 77 : The fprintf command used to display text/data output on the screen or to save it to a file output can be formatted number can be controlled Syntax fprintf(‘ text typed is as a string’) 77

To display text : To display text x=10;y=20; fprintf('the product is=') z=x*y; the product is=>> x=10;y=20; fprintf('the product is=\n') z=x*y; the product is= >> \n escape character \b backspace \t horizontal tab 78

To display mix of text and numerical : To display mix of text and numerical Syntax fprintf(‘text as a string %-5.2f additional text’,variable name) % - makes the spot where the number is inserted within the text -5.2f- formatting the elements (define the format of number) - flag (optional) 5.2 field width and precision (optional) f conversion character (required) variable name- who's value to be displayed 79

Slide 80 : 80

Slide 81 : 81

fprintf example : fprintf example clc clear all for i=1:10 j=i^2; fprintf('the i value of i is %5.2f \t and its square is %5.2f\n',i,j) end 82

Hints for C Users : Hints for C Users Some advice to users of C (or C++): You don't have to declare your variables. Semicolons on the end of lines suppress output. Use & and | instead of && and ||. To get bitwise operations (& and | in C) Everything is stored as a 2-dimensional array of data. Use parentheses to index into matrices, not brackets, and use A(i, j), not A[i][j]. 83

Slide 84 : All the operators are overloaded to work with matrices. The comment symbol is % and behaves like //. The output of Matlab functions can be assigned to vectors of variables, and often this is the only way to coerce the function to return certain outputs. In general, Matlab commands cannot span multiple lines unless you are using bracket notation to enter a matrix, or if you type the continuation operator ... before you press Enter. 84

Slide 85 : FUNCTIONS and Programming -II 85

Slide 86 : Many functions are progrmmed in MATLAB as built in functions EX: SIN(X),INV(A) Other than above –user defined functions Function file input output note: multi/single ,scalar, array- input/output 86

Slide 87 : The main future of functions is to have input and output Functions are used as subprograms in large programs( small ‘built in blocks’) Similar to basic fortran, pascal, and functions in C 87

Creating a function file and structure : Creating a function file and structure Definition line H1 Line Help text Function body 88

Structure of a file : Structure of a file Definition of function Input output arguments The H1 line and Help text lines Function body Local and Global variables Saving a function file Using a function file 89

Simple Example : Simple Example Find the cube of a number -> (x3) Type the code below into an .m file and save it as cube.m Set the Matlab directory appropriately In Matlab window, type cube(3), is the result correct? Now you have a reusable function that can calculate the cube of any number function [y] = cube(x) y = x*x*x; >> cube(3) Ans = 125 >> cube 1.75 Ans = 5.3594 90

Add Some Help : Add Some Help Find the cube of a number -> (x3) Add commented text between the funciton declaration and the first line of code Now type help cube in Matlab window function [y] = cube(x) % Put some text here y = x*x*x; >> help cube Put some text here 91

Find the cube of two numbers : Find the cube of two numbers Any numbers of inputs and outputs can be handled in a function For a simple example, extend the cube function to accept two inputs and find the cube of each function [y1, y2] = cube(x1, x2) % Put some text here y1 = x1*x1*x1; y2 = x2*x2*x2 >> cube(2,3) Ans = 4 ??? >> [a b] = cube(2,3) a = 8 b = 27 92

nargin : nargin Matlab will accept a function call with any number of inputs and outputs nargin can be used to find out how many inputs the user has provided It is automatically passed with the function function [y1, y2] = cube(x1, x2) If nargin == 1 y1 = x1*x1*x1; y2 = nan; elseif nargin == 2 y1 = x1*x1*x1; y2 = x2*x2*x2; end >> cube(2,3) Ans = 4 >> [a b] = cube(2,3) a = 8 b = 27 93

return : return return terminates computation of the function and returns whatever is calculated thus far function [y1, y2] = cube(x1, x2) If nargin == 1 y1 = x1*x1*x1; y2 = Nan; return end y1 = x1*x1*x1; y2 = x2*x2*x2; >> cube(2,3) Ans = 4 >> [a b] = cube(2,3) a = 8 b = 27 94

Find the Cube of Any Number of Numbers : Find the Cube of Any Number of Numbers Any ideas on how to accomplish this? Lets further extend the function to cube a vector of numbers Before we thought of the variables as scalars, now rethink the power of vectors function [y] = cube(x) % Put some text here y = x.^3; >> cube(2) Ans = 8 >> cube([2 3]) Ans = [8 27] 95

Slide 96 : Example of a script: r =100; theta = 12; x = r*cos(theta); y = r*sin(theta); >>Polar2Cart; 96

Slide 97 : Example of a function: function [x,y] = Polar2Cart(r,theta); x = r*cos(theta); y = r*sin(theta); >>[x,y] = Polar2Cart(r,theta); 97

Slide 98 : Write help for your function function [x,y] = Polar2Cart(r,theta); % This function convert Polar to Cartesian x = r*cos(theta); % Compute x component. y = r*sin(theta); % Compute y component. 98

Comparison between script file and function files : Comparison between script file and function files Both script and function files are saved with the extension .m (that is why they are sometimes called M-files). The first line in a function file is the function definition line. The variables in a function file are local. The variables in a script file are recognized in the Command Window. Script files can use variables that have been defined in the workspace. Script files contain a sequence of MATLAB commands (statements). Function files can accept data through input arguments and can return data through output arguments. When a function file is saved, the name of the file should be the same as the name of the function. 99

Inline functions : Inline functions An inline function is defined within the computer code (not as a separate file like a function file) and is then used in the code. Inline functions can be defined in any part of MATLAB. Inline functions are created with the inline command according to the following format: name=inline(‘math expression typed as a string’) The mathematical expression can have one or several independent variables. Any letter except i and j can be used for the independent variables in the expression. 100

Slide 101 : The mathematical expression can include any built-in or user-defined functions The expression must be written according to the dimension of the argument (element-by-element or linear algebra calculations). The expression can not include preassigned variables. Once the function is defmed it can be used by typing its name and a value for the argument (or arguments) in parenthesis . The inline function can also be used as an argument in other functions 101

Slide 102 : Let f = inline('sqrt(x.^2+y.^2)','x','y') f = Inline function: f(x,y) = sqrt(x.^2+y.^2) % You can evaluate this function in a usual way >>f(3,4) ans =5 102

Note that this function also works with arrays : Note that this function also works with arrays Let A = [1 2;3 4] and B = ones(2) Then C = f(A, B) C = 1.4142 2.2361 3.1623 4.1231 103

Slide 104 : 104

The feval command : The feval command The feval (function evaluate) command evaluates the value of a function for a given value (or values) of the function’s argument (or arguments). The format of the command is Variablename=feval(‘function name’,argument value) OR feval('functname', input parameters of function functname) 105

Slide 106 : The function name is typed as string, The function can be a built-in or a user-defmed function If there is more than one output argument, the arguments are separated with commas If there is more than one output argument, the variables on the left-hand side of the assignment operator are typed inside the brackets and separated with commas 106

Slide 107 : >> a=[1 2;4 3]; feval('inv',a) Finally It is obvious that there is no need to use the feval when there is chance of direct usage of funtions 107

fidopen,fidclose : fidopen,fidclose x = 0:1:2;y = sin(x); z = [x' y']; plot(x,y,'b.'); plot(z(:,1),z(:,2),'r*-'); fid = fopen('txtoutput.txt','w'); fprintf(fid,'%2.1f 20.17f\r\n',z'); fclose(fid); save matoutput z; 108

Function handles : Function handles It is used for storing of information and to use it in later stage This is created by two ways Using @ operator Using str2func function 109

Slide 110 : function rot_1 =func(t) rot_1=4*exp(-2*t); end 110

examples : examples %% fun1=@(x)x.^3+3*x^2+4 %% fx=@(x) x.^3+4*x.^2+5*x+10; %% ha2=str2func('func') %% ha1=@func 111

Condition Statements : It is often necessary to only perform matlab operations when certain conditions are met Relational and Logical operators are used to define specific conditions Simple flow control in matlab is performed with the ‘If’, ‘Else’, ‘Elseif’ and ‘Switch’ statements Condition Statements 112

Condition Statements : If, Else, and Elseif An if statement evaluates a logical expression and evaluates a group of commands when the logical expression is true The list of conditional commands are terminated by the end statement If the logical expression is false, all the conditional commands are skipped Execution of the script resumes after the end statement Basic form: if logical_expression commands end Condition Statements 113

Condition Statements : If, Else, and Elseif The elseif statement forces execution of the commands below the else statement if the original logical expression evaluates to false Only one list of commands can be executed Basic form: if logical_expression commands 1 elseif logical_expression_2 commands 2 elseif logical_expression_3 commands 3 end Condition Statements 114

If-elseif-else-end structure : If-elseif-else-end structure 115

MATLAB Programming : MATLAB Programming Flow Control: – if: if expression statements elseif expression statements else statements end Example1: if (a>b), disp(‘a>b’); end; Example2: if (a>b), disp(‘a>b’); else disp(‘a<=b’); end; Example3: if (a>b), disp(‘a>b’); elseif (a

Loops : Loops are an important component of flow control that enables matlab to repeat multiple statements in specific and controllable ways Simple repetition in matlab is controlled by two types of loops: For loops While loops Loops 117

Loops : For Loops The for loop executes a statement or group of statements a predetermined number of times Basic Form: for index = start:increment:end statements end ** If ‘increment’ is not specified, an increment of 1 is assumed by matlab Loops 118

Slide 119 : for n=0:10 x(n+1) = sin(pi*n/10); end ___________________________ A = zeros(10); for k=1:10 for l=1:10 A(k,l) = sin(k)*cos(l); end end _________________________ Same as k = 1:10; A = sin(k)'*cos(k); H = zeros(5); for k=1:5 for l=1:5 H(k,l) = 1/(k+l-1); end end H ___________________________ Cntr = 0; for i=1:100, Cntr = Cntr+i; end; 119

MATLAB Programming : MATLAB Programming Example2: Cntr = 0; for i=100:-2:0, Cntr = Cntr+i; end; Example3: Cntr = 0; for i=[1,2,5,12], Cntr = Cntr+ i; end; 120

Loops : While Loops The while loop executes a statement or group of statements repeatedly as long as the controlling expression is true Or This loop is used when the programmer does not know the number of repetitions a priori. Basic Form: while expression statements end Loops 121

Slide 122 : q = pi; while q > 0.01 q = q/2; end >>q q = 0.006 Flow Control: while: while expression statements end; Example1: Cntr = 100; while (Cntr>0), Cntr = Cntr – 1; end; 122

Syntax of the switch-case construction : Syntax of the switch-case construction switch expression (scalar or string) case value1 (executes if expression evaluates to value1) commands case value2 (executes if expression evaluates to value2) commands ... otherwise statements end Switch compares the input expression to each case value. Once the match is found it executes the associated commands. 123

Slide 124 : Example, if the floor is 0, set s to 1, if the floor is prime, add 1, otherwise, subtract 1: s = rand(1)*10 switch floor(s) case 0 s = 1 case {2, 3, 5, 7} s = s + 1 otherwise s = s - 1; end method = 'Bilinear'; switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') case 'nearest' disp('Method is nearest') otherwise disp('Unknown method.') end 124

In the following example a random integer number x from the set {1, 2, … , 10} is generated. Ifx = 1 or x = 2, then the message Probability = 20% is displayed to the screen. If x = 3 or 4 or 5,then the message Probability = 30% is displayed, otherwise the message Probability = 50% isgenerated. The script file switch utilizes a switch as a tool for handling all cases mentionedabove : In the following example a random integer number x from the set {1, 2, … , 10} is generated. Ifx = 1 or x = 2, then the message Probability = 20% is displayed to the screen. If x = 3 or 4 or 5,then the message Probability = 30% is displayed, otherwise the message Probability = 50% isgenerated. The script file switch utilizes a switch as a tool for handling all cases mentionedabove % Script file fswitch. x = ceil(10*rand); % Generate a random integer in {1, 2, ... , 10} switch x case {1,2} disp('Probability = 20%'); case {3,4,5} disp('Probability = 30%'); otherwise disp('Probability = 50%'); end Note use of the curly braces after the word case. This creates the so-called cell array rather than the one-dimensional array, which requires use of the square brackets. 125

Nested loops and nested conditional loops : Nested loops and nested conditional loops 126

The break and continue commands : The break and continue commands 127

The break command : The break command When inside a loop (for and while), the break command terminates the execution of the loop (the whole loop, not just the last pass). When the break command appears in a loop, MATLAB jumps to the end command of the loop and continues with the next command (does not go back to the for command of that loop). If the break command is inside a nested loop, only the nested loop is terminated. When a break command appears outside a loop in a script, or function file, it terminates the execution of the file. The break command is. usually used within a conditional statement. In loops it provides a method to terminate the looping process if some condition is met For example, if the number of loops exceeds a predetermined value, or an error in some numerical procedure is smaller than a predetermined value. When typed outside a loop, the break command provides a means to terminate the execution of a file, such as if data transferred into a function file is not consistent with what is expected. 128

Example : Example sum1=0; for k=1:10, sum1=sum1+k; if (sum1>20) break; end; fprintf(‘sum=%d\n’,sum1) end; 129

The continue command : The continue command • The continue command can be used inside a loop (for and while) to stop the present pass and start the next pass in the looping process. • The continue command is usually a part of a conditional statement. When MATLAB reaches the continue command, it does not execute the remaining commands in the loop, but skips to the end command of the loop and then starts a new pass. 130

Example : Example for k=1:10, if ((k>2)&&(k<7)), continue; end; fprintf(‘k=%d\n’,k) end; 131

Thank you : Thank you 132

Want to learn?

Sign up and browse through relevant courses.

Name:
Your Email:
Password:
Country:
Contact no:


Area code Number
Subjects you are interested in:
Word verification: (Enter the text as in image)


Sign Up Already a member? Sign In
I agree to WizIQ's User Agreement & Privacy Policy
Thesis123 an experts union
We provide you complete end to end project solutions
User
1 Member Recommends
3 Followers

Your Facebook Friends on WizIQ

Explore Similar Courses

Give live classes, create & sell online courses

Try it free Plans & Pricing

Connect