Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to MATLAB

Similar presentations


Presentation on theme: "Introduction to MATLAB"— Presentation transcript:

1 Introduction to MATLAB
MATLAB Basics Part I

2 Introduction Computation programming visualization
Introduction to MATLAB Introduction MATLAB MATLAB MATLAB Computation visualization programming

3 MATLAB Basics MATLAB working environment Variables and Constants
Introduction to MATLAB MATLAB Basics MATLAB working environment Variables and Constants Matrices and Vectors Operators Useful Functions

4 MATLAB Basics MATLAB working environment Variables and Constants
Introduction to MATLAB MATLAB Basics MATLAB working environment Variables and Constants Matrices and Vectors Operators Useful Functions

5 MATLAB working environment
Introduction to MATLAB MATLAB working environment I. Command Window The Command Window is the main window in which you can communicate with the MATLAB interpreter

6 MATLAB working environment
Introduction to MATLAB MATLAB working environment II. Punctuation and Command Line Editing Denotes a continuation character , Separates commands on a line ; Separates commands on a line and inhibits the display of intermediate results. % Denotes comment after this sign ! A system command follows this character MATLAB is case sensitive

7 MATLAB working environment
Introduction to MATLAB MATLAB working environment III. Work Space It is the area of memory containing all variables defined during MATLAB execution. View  workspace

8 MATLAB working environment
Introduction to MATLAB MATLAB working environment IV. Current Directory MATLAB maintains a current directory for the purpose of working with M and MAT files.

9 MATLAB working environment
Introduction to MATLAB MATLAB working environment V. Editor / Debugger A tool for creating scripts and functions (m-files) To run an m-file, type its name in the command window

10 MATLAB Basics MATLAB working environment Variables and Constants
Introduction to MATLAB MATLAB Basics MATLAB working environment Variables and Constants Matrices and Vectors Operators Useful Functions

11 Variables and Constants
Introduction to MATLAB Variables and Constants I. Variables Require no declaration or dimension statement The variable name must start with a letter followed by any number of letters, numbers and underscores Case sensitive Example num_students = 17 ; Course_name = ‘ Introduction to MATLAB ’ ; Number declaration String declaration

12 Variables and Constants
Introduction to MATLAB Variables and Constants II. Constants ans Most recent answer pi i, j Imaginary unit, -1 Inf Infinity NaN Not a number realmax Largest positive floating point number realmin Smallest positive floating point number eps Floating point accuracy e Power of 10 scale factor

13 Example a = 4+3i; b = 5+5i; c = 5; d = -3;
Introduction to MATLAB Example a = 4+3i; b = 5+5i; c = 5; d = -3; a*b , e = a + ans , f = c/0 , g = d/0 , f /g ans = i e = i Warning: Divide by zero. (Type "warning off MATLAB:divideByZero" to suppress this warning.) f = Inf g = -Inf NaN

14 MATLAB Basics MATLAB working environment Variables and Constants
Introduction to MATLAB MATLAB Basics MATLAB working environment Variables and Constants Matrices and Vectors Operators Useful Functions

15 Matrices and Vectors I. Entering matrices from command line or m-file
Introduction to MATLAB Matrices and Vectors  A matrix is a two-dimensional rectangular array of real or complex numbers I. Entering matrices from command line or m-file To enter a matrix, you have only to follow a few basic conventions: Separate the elements of a row with blanks or commas. Use a semicolon to indicate the end of each row. Surround the entire list of elements with square brackets, [ ].

16 Example Define the following matrix: 5 10 11 8 9 6 7 12 4 15 14 1
Introduction to MATLAB Example Define the following matrix: A = >>A = [ ; ; ; ]; A(2,2) A (1 , end) A(6) Notes The element in row i and column j of matrix A is denoted by A(i,j) (row-column subscript). It is also possible to refer to the elements of a matrix with a single subscript, A(k), (element colum wise index). "end" specifies maximum index value. 1 2 3 4 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

17 Any MATLAB expression can be entered as a matrix element
Introduction to MATLAB Any MATLAB expression can be entered as a matrix element >> b = [-2.8 , sqrt(-7) , (3 + 5i) *3/4 ]  b = i i If you store a value in an element outside of the matrix (using row-column subscript only), the size increases to accommodate the newcomer, for example : >>b(2, 5) = 17  MATLAB will modify the matrix to be,  b = i i If you try to use the value of an element outside of the matrix, for example: >>t = b(3, 1) MATLAB displays the following error message: ??? Index exceeds matrix dimensions.

18 II. Generating Matrices Using Built-in Functions
Introduction to MATLAB II. Generating Matrices Using Built-in Functions zeros (n,m) Creates n x m matrix of zeros ones (n,m) Creates n x m matrix of ones rand (n,m) Generates random vectors and matrices whose elements are uniformly distributed in the interval (0,1) randn (n,m) Generates random vectors and matrices whose elements are normally distributed with mean 0 and variance 1. Linspace (x1,x2,n) Creates linearly spaced vector of n points between x1 and x2 logspace(d1,d2,n) Creates logarithmically spaced vector of n points between decades 10^d1 and 10^d2. Magic(n) Creates magic squares of almost any size. (sum for an n-by-n magic square is ( n 3 + n)/2. pascal (n) Creates Pascal matrix. eye(n) Creates n x n identity matrix

19 Example Define the following matrix:
Introduction to MATLAB Define the following matrix: 1 – zeros matrix with dimensions (2x4) 2 – five’s matrix with dimensions (2x2) 3 – random matrix with dimensions (4x4) Example >> Z = zeros (2,4) Z = >> F = 5*ones(2,2) F = 5 5 5 5 >> R = randn(4,4) R = – –1.4410 – –0.3999 – –

20 Introduction to MATLAB
III. Concatenation Concatenation is the process of joining small matrices to make bigger ones. The pair of square brackets, [ ], is the concatenation operator. For example A = 5 10 B = C = A B C = [A B]

21 Example IV. Empty Matrices To define an empty matrix
Introduction to MATLAB Example >>A = [1 2 ; 3 4]; >>B = [A A+10; A+20 zeros(2) ] B = IV. Empty Matrices It is a matrices and arrays where one, but not all, of the dimensions is zero. To define an empty matrix U=[ ] or E = zeros(0,5)

22 MATLAB Basics MATLAB working environment Variables and Constants
Introduction to MATLAB MATLAB Basics MATLAB working environment Variables and Constants Matrices and Vectors Operators Useful Functions

23 Operators MATLAB’s operators fall into three categories:
Introduction to MATLAB Operators MATLAB’s operators fall into three categories: Arithmetic operators that perform numeric computations Relational operators that compare operands quantitatively, using operators like “less than” and “not equal to.” Logical operators that use the logical operators AND, OR, and NOT, with the result corresponding to TRUE (1) or FALSE (0).

24 A2 I. Arithmetic Operators Matrix operation Array operation A = 3 4 5
Introduction to MATLAB I. Arithmetic Operators A = A2 Matrix operation Array operation

25 The precedence rules for the arithmetic operators are:
Introduction to MATLAB The precedence rules for the arithmetic operators are: Matrix Operators comp. conj. transpose (') & power (^) unary plus (+) & unary minus (–) matrix multiplication (*), matrix right division (/) & matrix left division (\) addition (+) & subtraction (–) colon operator (:) Array Operators array transpose (.') & array power (.^), unary plus (+) & unary minus (–) array multiplication (.*) , array right division (./) & array left division (\) addition (+) & subtraction (–)

26 Examples A = [3 9 5] B = [2 1 5] comp = [ 1 + 2i 4 - 3i ]
Introduction to MATLAB Examples A = [ ] B = [ ] comp = [ 1 + 2i i ] Matrix Operations Array Operations C = A' C = 3 9 5 C = A.' C = 3 D = comp' D = i i D = comp.' i i E = A^2 ??? Error using ==> ^ Matrix must be square. E = A.^2 E = F = A*B ??? Error using ==> run Error using ==> * Inner matrix dimensions must agree F = A.*B F =

27 The result on the MATLAB
Introduction to MATLAB Examples A = [ ] B = [ ] b = 3 Operator & operands The result on the MATLAB display C = sqrt(A(2)) + 2*B(1) C = 7 D = A./B.^2 D = E = A.\B.^2 E = F= (A.\B).^2 F = G = A./b^2 G = H = A/b^2 H = A + b ans = b * A Note: For array operation x/y = y\x

28 The Colon Operator (:) operators.It occurs in several different forms.
Introduction to MATLAB The Colon Operator (:)   The colon, (:) is one of MATLAB’s most important operators.It occurs in several different forms. 1. Defining Vectors   The expression 1 : 10 is a row vector containing the integers from 1 to 10 with unit spacing >> t = 1 :10 t = To obtain non-unit spacing, specify an increment. For exampl   >> theta = 0 : pi/4 : pi theta = >> x = 100 : –7 : 50 x =

29 Introduction to MATLAB
2.Indexing The colon, by itself, refers to all the elements in a row or column of a matrix. Subscript expressions involving colons refer to portions of a matrix, A(1:k, j) is the first k elements of the jth column of A. A( : , [ 3 4]) Example 1 2 3 4 6 5 1 16 6 2 11 3 13 21 26 60 5 7 12 10 17 28 22 8 27 9 18 23 42 4 14 15 19 24 71 29 31 41 20 25 56 30 A(1 : 5 , 6) A(1 : end , end) A( : , 6) A( : , end) A(26 : 30) A(26 : end) A = 1 2 3 4 5 row-column subscript element wise index A(2 , 1) A(2) A(3 : 5 , 1 : 2)

30 Examples a = magic (3) b = a(1 : 2, 2 : 3) c = a(3 : -1 : 1, : )
Introduction to MATLAB Examples a = magic (3) b = a(1 : 2, 2 : 3) c = a(3 : -1 : 1, : ) d = [ a c( : , [ 1 3])] a = b = 1 6 5 7 c =  d =

31 Introduction to MATLAB
Note: You can delete rows and columns from a matrix using colons and just a pair of square brackets. Example B = B = magic (4); B( : , 3) = [ ] B = Tip  If you delete a single element from a matrix, the result isn’t a matrix anymore. So, expressions like B(1,2) = [ ] result in an error. However, using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So  B(2:2:10) = [ ] results in B = This changes B to

32 II. Relational Operators
Introduction to MATLAB II. Relational Operators There are six relational operators: < Less than > Greater than <= Less than or equal to >= Greater than or equal to = = Equal to ~= Not equal to MATLAB’s relational operators compare corresponding elements of arrays with equal dimensions and sizes. For the case where one operand is a scalar and the other is not, MATLAB applies the scalar against every element of the other operand (scalar expansion). Locations where the specified relation is true receive the value 1. Locations where the relation is false receive the value 0.

33 Examples Introduction to MATLAB >> A = [ ; –1; ]; B = [ ; – ; 4 –1 7]; >> A < B ans = 1 0 0 0 1 1 1 0 1 >> A = [ ; ; ]; B = [ ; ; ]; >> A == B ans = Note: >> isequal (A,B) ans =0 >> A = [2 7 0; 9 0 2; ]; B = 2; >> A == B ans =

34 MATLAB provides a number of logical functions. These include:
Introduction to MATLAB isempty(A) returns logical true (1) if A is an empty array and logical false (0) otherwise. all(A) If A is a vector, all(A) returns 1 if all elements are nonzero and 0 otherwise. If A is a matrix, all(A) operates on the columns of A, returning a row vector of 1's and 0's. all(A,2) operates on the rows of A. , returning a column of 1's and 0's. any(A) True if any element of vector is nonzero. “any” function is applied to vectors and matrices and uses DIM option as “all” function. isfinite(A) returns an array the same size as A containing logical true (1) where the elements of the array A are finite and logical false (0) where they are infinite or NaN. isinf(A) returns an array the same size as A containing logical true (1) where the elements of A are +Inf or –Inf and logical false (0) where they are not. isnan(A) returns an array the same size as A containing logical true (1) where the elements of A are NaNs and logical false (0) where they are not. isreal(A) returns 1 if all elements of A are real numbers, and 0 if either A is not a numeric array, or if any element of A has a nonzero imaginary component. isreal always returns 1 for a string matrix A.

35 Example A=[5 2 4 0 3 1 8 ]; B = magic (5); B(2,3) = 0 ; B(4,4) = 0;
Introduction to MATLAB Example A=[ ]; B = magic (5); B(2,3) = 0 ; B(4,4) = 0; C = all (A) D = any (A) E = all (A<9) F = all (B) G = all(B,2) B = C = D = 1 E = F = G =

36 Example A = [0 1 5; 2 NaN –inf]; B = [0 0 15; 2 5 inf]; C = A ./ B;
Introduction to MATLAB Example A = [ ; 2 NaN –inf]; B = [ ; inf]; C = A ./ B; D = isfinite (C) E = isnan (C) F = isinf (C) G= isreal (C) D = E =   F = G = C = NaN Inf NaN NaN

37 III. Logical Operators & AND | OR ~ NOT
Introduction to MATLAB III. Logical Operators & AND | OR ~ NOT MATLAB’s logical operators compare corresponding elements of arrays with equal dimensions and sizes. For the case where one operand is a scalar and the other is not, MATLAB tests the scalar against every element of the other operand. Locations where the specified relation is true receive the value 1. Locations where the relation is false receive the value 0. The xor(a,b) function performs an exclusive OR on its operands. In addition to these logical operators, the bitfun directory contains a number of functions that perform bitwise logical operations such as bitand, bitor , bitxor……..

38 Example a = 1 : 9 b = 9 - a c = b - (a > 2) d =~(a > 4)
Introduction to MATLAB Example a = 1 : 9 b = 9 - a c = b - (a > 2) d =~(a > 4) e = (a > 2)& (a < 6) a = b =  c = d = e =

39 Example a = 5 ; b = 9; c = bitand(a,b) d = bitor(a,b) c = 1 d = 13
Introduction to MATLAB Example a = 5 ; b = 9; c = bitand(a,b) d = bitor(a,b) c = 1 d = 13

40 Useful functions I. The find Function
Introduction to MATLAB Useful functions I. The find Function The find function determines the indices of nonzero array elements or those meet a given logical condition. Syntax I = find(A) returns the indices of the matrix A that are non-zero in form of element wise index . [I,J] = find (A) returns the row and column indices of the nonzero entries in the matrix A.

41 Example a = [2 3 NaN; 0 NaN 6]; k = find(isnan(a))
Introduction to MATLAB Example a = [2 3 NaN; 0 NaN 6]; k = find(isnan(a)) [I J] = find(a > 3) k = I = 2 J = 3 a = NaN 0 NaN

42 II. The trigonometric Function
Introduction to MATLAB II. The trigonometric Function sin (x) Sine sinh (x) Hyperbolic sine asin (x) Inv. sine asinh (x) Inv. hyper. Sine cos (x) Cosine cosh (x) Hyberbolic cosine acos (x) Inv. cosine acosh (x) Inv. hyber. Cosine tan (x) Tangent tanh (x) Hyper. Tangent atan (x) Inv. Tangent atanh (x) Inv. hyber. Tangent csc (x) Cosecant csch (x) Hyperbolic cosecant acsc (x) Inv. Cosecant acsch (x) Inv. hyper. cosecant sec (x) Secant sech (x) Hyberbolic Secant asec (x) Inv. Secant asech (x) Inv. hyber. Secant cot (x) Cotangent coth (x) Hyper. Cotangent acot (x) Inv. Cotangent acoth (x) Inv. hyber. Cotangent Tip : Trigonometric functions use radians but not degree; however, the angle in graphics (polar plot) views in degree.

43 II. The exponential Function
Introduction to MATLAB II. The exponential Function Exp (x) Exponential. Log(x) Natural logarithm. Pow2(x) Base 2 power log2(x) Base 2 logarithm. log10(x) Common (base 10) logarithm nextpow2(x) Next higher power of 2.,returns the first P such that 2^P >= abs(x)

44 III. The Rounding and Remainder Function
Introduction to MATLAB III. The Rounding and Remainder Function Fix (x) rounds the elements of x to the nearest integers towards zero. Round(x) rounds the elements of x to the nearest integers. Sign(x) returns 1 if the element is greater than zero, 0 if it equals zero and -1 if it is less than zero. For complex x, sign(x) = x ./ abs(x). Mod(x,y) mod(x,y) = x - y.*floor(x./y) if y ~= 0. By convention, mod(x,0) is x. The input x and y must be real arrays of the same size, or real scalars. ceil (x) rounds the elements of x to the nearest integers towards infinity. floor (x) rounds the elements of x to the nearest integers towards minus infinity. rem(x,y) rem(x,y) = x - y.*fix(x./y) if y ~= 0. By convention, rem(x,0) is NaN. The input x and y must be real arrays of the same size, or real scalars.

45 Example x pow2(x) nextpow2(x) 1 2 3 8 x fix(x) round(x) floor(x)
Introduction to MATLAB Example x pow2(x) nextpow2(x) 1 2 3 8 x fix(x) round(x) floor(x) ceil(x) 3.5 3 4 3.2 3.7 -3.5 -3 -4 -3.2 -3.7 x y rem(x,y) mod(x,y) 5 2.2 0.6000 -2.2 -5 1.6000

46 Example IV. The Complex Functions abs(x)
Introduction to MATLAB IV. The Complex Functions abs(x) Absolute value and complex magnitude. angle (x) returns the phase angles, in radians, of a matrix with complex elements. conj(x) Complex conjugate. imag(x) Complex imaginary part. real(x) Complex real part. unwrap(x) Unwrap phase angle, corrects the radian phase angles in array x by adding multiples of ±2 when absolute jumps between consecutive array elements are greater than  radians. Example x=[-13.5 : 5 : 13.5] unwrap(x) x = ans =

47 V. Selected elementary functions for matrices
Introduction to MATLAB V. Selected elementary functions for matrices min (A) Smallest component. For vectors, min (A) is the smallest element in A. For matrices, min(A) is a row vector containing the minimum element from each column. max (A) Largest component. length (A) If A is a vector, length (A) returns the length (number of elements) of the vector. If A is a matrix, length (A) returns the number of columns in the matrix D = size(A) [M,N] = size(A)  M = size(A, DIM) For M-by-N matrix A, returns the two-element row vector D = [M, N] containing the number of rows and columns in the matrix. returns the number of rows and columns in separate output variables returns the length of the dimension specified by the scalar DIM. DIM = 1 for rows and DIM= 2 for columns sum(A) sum(A,DIM) Sum of elements. For vectors, sum(A) is the sum of the elements of A. For matrices, sum(A) is a row vector with the sum over each column.  sums along the dimension DIM. sort(A) Sort in ascending order. For vectors, sort(A) sorts the elements of A in ascending order. For matrices, sort (A) sorts each column of A in ascending order.

48 Example A = [3 14 5 7; 1 4 0 12; 1 8 2 0]; B = min(A) , C= max(A)
Introduction to MATLAB Example A = [ ; ; ]; B = min(A) , C= max(A) D = length(A), E = size(A) F = sum (A) , G = sort(A) B = C = D= E =   F = G =

49 VI. The clear Command It removes items from memory clear
Introduction to MATLAB It removes items from memory clear Clears all variables and function from the workspace. clear name or clear name1, name2, name3 removes just the M-file or MEX-file function or variable “name” from the workspace. If name is global variable, it is removed from the current workspace, but left accessible to any functions declaring it global. clear global clear global vari Clears all global variables from all workspaces Clears the “vari” global variables from all workspaces clear all Removes all local and global variables, functions, and MEX-files from memory, leaving the workspace empty. clear functions clear function_name Clears all the currently compiled M-functions from memory. Clears specified function from the workspace Tip: You can use wildcards (*) to remove items selectively. For instance, clear my* removes any variables whose names begin with the string “my.”

50 VII. The Base Number Conversion Functions
Introduction to MATLAB VII. The Base Number Conversion Functions dec2base ( D , b ) dec2base (D , b , n ) If D is a scalar, dec2base returns the representation of D as a string in base b. If D is a real matrix, dec2base converts D in a columnwise manner to a character array where each row is interpreted as a base b string. Scalar D or elements of matrix D must be a non-negative integer smaller than 2^52 and b must be an integer between 2 and 36 Produces a representation with at least n digits. Base2dec (S , b) Converts the string number S of base b into its decimal equivalent, b = 2 : 36. If S is a character or cell array, each row is interpreted as a base b string. dec2bin ( D , n  ) Returns the binary representation of B as a string with at least n bits. bin2dec (B) Converts the binary string B to decimal integer. dec2hex ( D , n  ) Convert the decimal integer D to hexadecimal string with at least n digits. hex2num (Hs) Converts the hexadecimal string H to decimal integer. Convert IEEE hexadecimal to double precision number. Hs is a 16 character string containing a IEEE hexadecimal number. Fewer than 16 characters are padded on the right with zeros.

51 Introduction to MATLAB
Example a = [32 , 2 ; 16 , 2], b = {'100101',' '}, c = dec2bin(a) class (c) d = dec2base(8,8,4) e = bin2dec(b) c = 100000 010000 000010 ans = char d = 0010  e = 37 272 columnwise conversion


Download ppt "Introduction to MATLAB"

Similar presentations


Ads by Google