Introduction to Matlab By: Dr. Maher O. EL-Ghossain
Outline: q What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control Using of M-File Writing User Defined Functions Conclusion
What is Matlab? Matlab is basically a high level language which has many specialized toolboxes for making things easier for us How high? Matlab High Level Languages such as C, Pascal etc. Assembly
What are we interested in? Matlab is too broad for our purposes in this course. The features we are going to require is Series of Matlab commands m-files Matlab Command Line mat-files Input Output capability functions Command execution like DOS command window Data storage/ loading
Matlab Screen Command Window q type commands Current Directory q View folders and m-files Workspace q q View program variables Double click on a variable to see it in the Array Editor Command History q q view past commands save a whole session using diary
Notes for working in the Command Window: To type a command the cursor must be placed next to the command prompt ( >> ). Once a command is typed and the Enter key is pressed, the command is executed. Several commands can be typed in the same line. This is done by typing a comma between the commands. When the Enter key is pressed the commands are executed in order from left to right. A previously typed command can be recalled to the command prompt with the uparrow key ( ). When the command is displayed at the command prompt, it can be modified if needed and then executed. The down-arrow key ( ) can be used to move down the list of previously typed commands.
The semicolon ( ; ): When a command is typed in the Command Window and the Enter key is pressed, the command is executed. If a semicolon ( ; ) is typed at the end of a command the output of the command is not displayed. Typing %: When the symbol % (percent) is typed at the beginning of a line, the line is designated as a comment. This means that when the Enter key is pressed the line is not The clc command: The clc command (type clc and press Enter) clears the Command Window.
The Command History Window: The Command History Window lists the commands that have been entered in the Command Window. This includes commands from previous sessions. A command in the Command History Window can be used again in the Command Window. By double-clicking on the command, the command is reentered in the Command Window and executed.
1.3 ARITHMETIC OPERATIONS WITH SCALARS In this chapter we discuss only arithmetic operations with scalars, which are numbers. As will be explained later in the chapter, numbers can be used in arithmetic calculations directly (as with a calculator) or they can be assigned to variables, which can subsequently be used in calculations. Operation Symbol Example Addition + 5 + 3 Subtraction 5 3 Multiplication * 5 * 3 Right division / 5 / 3 Left division \ 5 \3 = 3 / 5 Exponentiation ^ 5 ^ 3 (means 5 ^ 3= 125)
Order of Precedence MATLAB executes the calculations according to the order of precedence displayed below. This order is the same as used in most calculators. Precedence Mathematical Operation First Parentheses. For nested parentheses, the innermost are executed first. Second Exponentiation. Third Multiplication, division (equal precedence). Fourth Addition and subtraction
DISPLAY FORMATS The user can control the format in which MATLAB displays output on the screen. In the output format is fixed-point with four decimal digits (called short), which is the default format for numerical values. formats can be obtained by typing help format in the Command Window.
ELEMENTARY MATH BUILT-IN FUNCTIONS In addition to basic arithmetic operations, expressions in MATLAB can include functions. MATLAB has a very large library of built-in functions. A function has a name and an argument in parentheses. For example, the function that calculates the square root of a number is sqrt(x).
DEFINING SCALAR VARIABLES A variable is a name made of a letter or a combination of several letters (and digits) that is assigned a numerical value. Once a variable is assigned a numerical value, it can be used in mathematical expressions, in functions, and in any MATLAB statements and commands. A variable is actually a name of a memory location. When a new variable is defined, MATLAB allocates an appropriate memory space where the variable s assignment is stored. we consider only variables that are assigned numerical values that are scalars.
Rules About Variable Names A variable can be named according to the following rules: Must begin with a letter. Can be up to 63 characters long. Can contain letters, digits, and the underscore character. Cannot contain punctuation characters (e.g., period, comma, semicolon). MATLAB is case sensitive: it distinguishes between uppercase and lowercase letters. For example, AA, Aa, aa, and aa are the names of four different variables. No spaces are allowed between characters (use the underscore where a space is desired). Avoid using the name of a built-in function for a variable (i.e., avoid using cos, sin, exp, sqrt, etc.). Once a function name is used to define a variable, the function cannot be used.
USEFUL COMMANDS FOR MANAGING VARIABLES The following are commands that can be used to eliminate variables or to obtain information about variables that have been created.. Command Outcome clear Removes all variables from the memory. clear x y z Removes only variables x, y, and z from the memory. who Displays a list of the variables currently in the memory. whos Displays a list of the variables currently in the memory and their sizes together with information about their bytes and class. 1
SCRIPT FILES A script file is a sequence of MATLAB commands, also called a program. When a script file runs (is executed), 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 a semicolon at the end), the output is displayed in the Command Window. Script files are also called M-files because the extension.m is used when they are saved. 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 21
In the File menu, select New, and then select Script. An open Editor/Debugger Window is shown 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 22
Current Folder 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 23
Creating Arrays The simplest array ( one-dimensional) is a row or a column of numbers. A more complex array (two dimensional) is a collection of numbers arranged in rows and columns. One use of arrays is to store information and data, as in a table. In science and engineering, one-dimensional arrays frequently represent vectors, and two-dimensional arrays often represent matrices: CREATING A ONE-DIMENSIONAL ARRAY (VECTOR): A one-dimensional array is a list of numbers arranged in a row or a column. The position of point A can be expressed in terms of a position vector ra = 2i + 4j +5k where i, j, and k are unit vectors in the direction of the x, y, and z axes, respectively. The numbers 2, 4, and 5 can beused to define a row or a column vector. Creating a vector from a known list of numbers: The vector is created by typing the elements (numbers) inside square brackets [ ]. variable_name = [ type vector elements ] 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 24
Creating a vector with constant spacing by specifying the first term, the spacing, and the last term: variable_name = [m:q:n] or variable_name = m:q:n 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 25
Creating a vector with linear (equal) spacing by specifying the first and last terms, and the number of terms: A vector with n elements that are linearly (equally) spaced in which the first element is xi and the last element is xf can be created by typing the linspacecommand (MATLAB determines the correct spacing): commanvariable_name = linspace(xi,xf,n)
CREATING A TWO-DIMENSIONAL ARRAY (MATRIX) A two-dimensional array, also called a matrix, has numbers in rows and columns. Matrices play an important role in linear algebra and are used in science and engineering to describe many physical quantities. In a square matrix the number of rows and the number of columns is equal. For example, the matrix 7 4 9 3 8 1 3 3 matrix 6 5 3 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 27
A m x n matrix has m rows and n columns, and m By n is called the size of the matrix. variable_name = [1st row elements; 2nd row elements; 3 rd row elements;... ; last row elements] 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 28
The zeros, ones and, eye Commands The zeros(m,n), ones(m,n), and eye(n) commands can be used to create matrices with m rows and n columns in which all elements are the numbers 0 and 1 0respectively.and eye(n) create square matrix with n rows and n columns in which th diagonal elements are equal to 1 and the rest of the elements are 0. 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 29
NOTES ABOUT VARIABLES IN MATLAB 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, vector, or matrix it can be changed to 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 be reduced to a vector or a scalar. 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 30
Matrix The address of an element in a matrix is its position, defined by the row number and the column number where it is located. For a matrix assigned to a variable ma, ma(k,p) refers to the element in row k and column p. Ma= 3 11 6 5 4 7 10 2 13 9 0 8 For example, if the matrix is: then ma(1,1) = 3 and ma(2,3) = 10. 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 31
USING A COLON : IN ADDRESSING ARRAYS A colon can be used to address a range of elements in a vector or a matrix. For a vector: va(:) Refers to all the elements of the vector va (either a row or a column vector). va(m:n) Refers to elements m through n of the vector va. example For a matrix: A(:,n) Refers to the elements in all the rows of column n of the matrix A. A(n,:) Refers to the elements in all the columns of row n of the matrix A. A(:,m:n) Refers to the elements in all the rows between columns m and n of the matrix A. A(m:n,:) Refers to the elements in all the columns between rows m and n of the matrix A. A(m:n,p:q) Refers to the elements in rows m through n and columns p through q of the matrix A.
ADDING ELEMENTS TO EXISTING VARIABLES Adding elements to a vector:
Adding elements to a matrix: Rows and/or columns can be added to an existing matrix by assigning values tothe new rows or columns.
DELETING ELEMENTS An element, or a range of elements, of an existing variable can be deleted by reassigning nothing to these elements.
BUILT-IN FUNCTIONS FOR HANDLING ARRAYS MATLAB has many built-in functions for managing and handling arrays. Some of these are listed below
ELEMENT-BY-ELEMENT OPERATIONS 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 54
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 55
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 56
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 57
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 58
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 59
PROGRAMING WITH MATLAB Using Script Files and Managing Data A script file is a list of MATLAB commands, called a program, that is saved in a file. When the script file is executed (run), MATLAB executes the commands. How to create, save, and run a simple script file in which the commands are executed in the order in which they are listed, and in which all the variables are defined within the script file. 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 60
THE MATLAB WORKSPACE AND THE WORKSPACE WINDOW The MATLAB workspace consists of the set of variables (named arrays) that are defined and stored during a MATLAB session. It includes variables that have been defined in the Command Window and variables defined when script files are executed.
INPUT TO A SCRIPT FILE When a script file is executed, the variables that are used in the calculations within the file must have assigned values. In other words, the variables must be in the workspace.
Programming in MATLAB RELATIONAL AND LOGICAL OPERATORS: Relational operators: Relational operators in MATLAB are: Relational operator Description < Less than > Greater than <= Less than or equal to >= Greater than or equal to = = Equal to ~= Not Equal to
CONDITIONAL STATEMENTS Examples: If a < b if c >= 5 if a == b if a ~= 0 if (d<h)&(x>7) if (x~=13) (y<0)
The if-end Structure 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 73
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 74
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 75
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 76
EXAMPLE 8 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 77
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 78
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 79
while-end Loops 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 80
EXAMPLE 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 81
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 82
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 83
PLOTS, Polynomials, Curve Fitting, and Interpolation Two-Dimensional Plots: THE plot COMMAND plot(x,y) 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 84
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 85
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 86
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 87
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 88
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 89
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 90
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 91
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 92
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 93
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 94
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 95
Polynomials, Curve Fitting, and Interpolation POLYNOMIALS 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 96
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 97
EXAMPLE 10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 98
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 99
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 100
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 101
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 102
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 103
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 104
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 105
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 106
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 107
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 108
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 109
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 110
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 111
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 112
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 113
10/29/2016 11:46:52 AM Dr Maher O. El-Ghossain 114
Array, Matrix a vector x = [1 2 5 1] x = 1 2 5 1 a matrix x = [1 2 3; 5 1 4; 3 2-1] x = 1 2 3 5 1 4 3 2-1 transpose y = x y = 1 2 5 1
Long Array, Matrix t =1:10 t = 1 2 3 4 5 6 7 8 9 10 k =2:-0.5:-1 k = 2 1.5 1 0.5 0-0.5-1 B = [1:4; 5:8] x = 1 2 3 4 5 6 7 8
Generating Vectors from functions zeros(m,n) MxN matrix of zeros ones(m,n) MxN matrix of ones rand(m,n) MxN matrix of uniformly distributed random numbers on (0,1) x = zeros(1,3) x = 0 0 0 x = ones(1,3) x = 1 1 1 x = rand(1,3) x = 0.9501 0.2311 0.6068
Matrix Index The matrix indices begin from 1 (not 0 (as in C)) The matrix indices must be positive integer Given: A(-2), A(0) Error:??? Subscript indices must either be real positive integers or logicals. A(4,2) Error:??? Index exceeds matrix dimensions.
Concatenation of Matrices x = [1 2], y = [4 5], z=[ 0 0] A = [ x y] 1 2 4 5 B = [x ; y] 1 2 4 5 C = [x y ;z] Error:??? Error using ==> vertcat CAT arguments dimensions are not consistent.
Operators (arithmetic) +addition - subtraction * multiplication / division ^power complex conjugate transpose
Matrices Operations Given A and B: Addition Subtraction Product Transpose
Operators (Element by Element).* element-by-element multiplication./ element-by-element division.^ element-by-element power
The use of. Element Operation A = [1 2 3; 5 1 4; 3 2 1] A = 1 2 3 5 1 4 3 2-1 x = A(1,:) x= 1 2 3 y = A(3,:) y= 3 4-1 b = x.* y b= 3 8-3 c = x. / y c= 0.33 0.5-3 d = x.^2 d= 1 4 9 K= x^2 Erorr:??? Error using ==> mpower Matrix must be square. B=x*y Erorr:??? Error using ==> mtimes Inner matrix dimensions must agree.
Basic Task: Plot the function sin(x) between 0 x 4π Create an x-array of 100 samples between 0 and 4π. >>x=linspace(0,4*pi,100); Calculate sin(.) of the x-array 1 0.8 >>y=sin(x); Plot the y-array >>plot(y) 0.6 0.4 0.2 0-0.2-0.4-0.6-0.8-1 0 10 20 30 40 50 60 70 80 90 100
Plot the function e -x/3 sin(x) between 0 x 4π Create an x-array of 100 samples between 0 and 4π. >>x=linspace(0,4*pi,100); Calculate sin(.) of the x-array >>y=sin(x); Calculate e -x/3 of the x-array >>y1=exp(-x/3); Multiply the arrays y and y1 >>y2=y*y1;
Plot the function e -x/3 sin(x) between 0 x 4π Multiply the arrays y and y1 correctly >>y2=y.*y1; Plot the y2-array >>plot(y2) 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0-0.1-0.2-0.3 0 10 20 30 40 50 60 70 80 90 100
Display Facilities 0.7 plot(.) Example: >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y) >>plot(x,y) stem(.) 0.6 0.5 0.4 0.3 0.2 0.1 0-0.1-0.2-0.3 0 10 20 30 40 50 60 70 80 90 100 0.7 0.6 0.5 0.4 0.3 Example: >>stem(y) >>stem(x,y) 0.2 0.1 0-0.1-0.2-0.3 0 10 20 30 40 50 60 70 80 90 100
Display Facilities title(.) >>title( This is the sinus function ) xlabel(.) >>xlabel( x (secs) ) ylabel(.) sin(x) 1 0.8 0.6 0.4 0.2 0-0.2-0.4-0.6 This is the sinus function >>ylabel( sin(x) ) -0.8-1 0 10 20 30 40 50 60 70 80 90 100 x (secs)
Operators (relational, logical) == Equal to ~= Not equal to < Strictly smaller > Strictly greater <= Smaller than or equal to >= Greater than equal to & And operator Or operator
Flow Control if for while break.
Control Structures If Statement Syntax if (Condition_1) Matlab Commands elseif (Condition_2) Matlab Commands elseif (Condition_3) Matlab Commands else Matlab Commands end Some Dummy Examples if ((a>3) & (b==5)) Some Matlab Commands; end if (a<3) Some Matlab Commands; elseif (b~=5) Some Matlab Commands; end if (a<3) Some Matlab Commands; else Some Matlab Commands; end
Control Structures For loop syntax for i=index_array Matlab Commands end Some Dummy Examples for i=1:100 Some Matlab Commands; end for j=1:3:200 Some Matlab Commands; end for m=13:-0.2:-21 Some Matlab Commands; end for k=[0.1 0.3-13 12 7-9.3] Some Matlab Commands; end
Control Structures While Loop Syntax while (condition) end Matlab Commands Dummy Example while ((a>3) & (b==5)) Some Matlab Commands; end
Use of M-File Click to create a new M-File Extension.m A text file containing script or function or program to run
Use of M-File Save file as Denem430.m If you include ; at the end of each statement, result will not be shown immediately
Writing User Defined Functions Functions are m-files which can be executed by specifying some inputs and supply some desired outputs. The code telling the Matlab that an m-file is actually a function is function out1=functionname(in1) function out1=functionname(in1,in2,in3) function [out1,out2]=functionname(in1,in2) You should write this command at the beginning of the m-file and you should save the m-file with a file name same as the function name
Writing User Defined Functions Examples q Write a function : out=squarer (A, ind) Which takes the square of the input matrix if the input indicator is equal to 1 And takes the element by element square of the input matrix if the input indicator is equal to 2 Same Name
Writing User Defined Functions Another function which takes an input array and returns the sum and product of its elements as outputs The function sumprod(.) can be called from command window or an m-file as
Notes: % is the neglect sign for Matlab (equaivalent of // in C). Anything after it on the same line is neglected by Matlab compiler. Sometimes slowing down the execution is done deliberately for observation purposes. You can use the command pause for this purpose pause %wait until any key pause(3) %wait 3 seconds
Useful Commands The two commands used most by Matlab users are >>help functionname >>lookfor keyword
Thank You