matlab basics - lnm institute of information technology · matlab basics vector: array with one...

Post on 30-Sep-2020

6 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

MATLAB BASICS

AJIT PATEL

Introduction to MATLABEEVFN-2013

MATLAB Review

� What is Matlab?� Matlab Screen� Variables, array, matrix, indexing � Matrices & Vectors � Operators (Arithmetic, relational, logical )� Display Facilities� Flow Control� Built-In Functions � Script & Function M-files

What is MATLAB?

� Computational Software � From The MathWorks: www.mathworks.com� Algorithm Development � Environment � MATrix LABoratory � Matlab is basically a high level language

which has many specialized toolboxes for making things easier for us

Matlab Screen

� Command Window� type commands

� Current Directory� View folders and m-files

� Workspace� View program variables� Double click on a variable

to see it in the Array Editor

� Command History� view past commands� save a whole session

using diary

Getting MATLAB Help

• Type one of the following commands in the command window:>>help – lists all the help topics>>help topic – provides help for the

specified topic>>help command – provides help for

the specified command>>helpwin – opens a separate help

window for navigation>>Lookfor keyword – search all M-

files for keyword

• Online resource

Simple Mathematic calculations

in command window� >> 1+1

ans =2

� >> 5-6ans =

-1� >> 7/8

ans =0.8750

� >> 9*2ans =

18

Syntax

� MATLAB syntax for entering commands:

>> x=1;

>> y=2

y =

2

>> plot(x,y,...

’r.’)

� Syntax:

� ; - ends command, suppresses output

� - ends command, allows output

� ... - allows to continue entering a statement in the next line

8

Variables and Arrays

� Array : A collection of data values organized into rows and columns, and known by a single name.

Row 1

Row 2

Row 3

Row 4

Col 1 Col 2 Col 3 Col 4 Col 5

arr(3,2)

9

Arrays

� The fundamental unit of data in MATLAB

� Scalars are also treated as arrays by MATLAB (1 row and 1 column).

� Row and column indices of an array start from 1.

� Arrays can be classified as vectors andmatrices .

10

MATLAB BASICS

� Vector: Array with one dimension

� Matrix: Array with more than one dimension

� Size of an array is specified by the number of rowsand the number of columns, with the number ofrows mentioned first (For example: m x n array).

Total number of elements in an array is theproduct of the number of rows and the number ofcolumns.

11

MATLAB BASICS

1 23 45 6

a= 3x2 matrix � 6 elements

b=[1 2 3 4] 1x4 array � 4 elements, row vector

c=135

3x1 array � 3 elements, column vector

a(2,1)=3 b(3)=3 c(2)=3

Row # Column #

12

Variables

� A region of memory containing an array, which is known by a user-specified name .

� Contents can be used or modified at any time.

� Variable names must begin with a letter, followed by any combination of letters, numbers and the underscore (_)character. Only the first 31 characters are significant.

� The MATLAB language is Case Sensitive. NAME, name and Name are all different variables.

Give meaningful (descriptive and easy-to-remember) names for the variables. Never define a variable with the same name as a MATLAB function or command.

Variables

� No need for types. i.e.,

� All variables are created with double precision unless specified and they are matrices.

� After these statements, the variables are 1x1 matrices with double precision

int a;double b;float c;

Example:>>x=5;>>x1=2;

Variables

� Begin with an alphabetic character: a � Case sensitive: a, A � Data type detection: a=5; a='ok'; a=1.3 � Default output variable: ans� Built-in constants: pi i j Inf� clear removes variables � who lists variables � Special characters � [] () {} ; % : = . ………… @

Variables (contd.)• Special variables:

– ans : default variable name for the result.– pi : π = 3.1415926 ……– eps : ε= 2.2204e-016, smallest value by which two numbers can

differ– inf : ∞, infinity – NAN or nan : not-a-number

• Commands involving variables:– who : lists the names of the defined variables– whos : lists the names and sizes of defined variables– clear : clears all variables– clear name: clears the variable name– clc : clears the command window– clf : clears the current figure and the graph window– Ctrl + C : Aborts calculation

Variables (contd.)

� Matlab allows infinity as value:

>> x = 1/0x =

Inf

>> x = 1.e1000x =

Inf

>> x = log(0)x =

Inf

>> x = 0/0x =

NaN

>> x = inf/infx =

NaN

>> x = inf * 0x =

NaN

� Other value NaN– not a number:

17

MATLAB BASICS

Common types of MATLAB variables

� double: 64-bit double-precision floating-point numbersThey can hold real or complex numbers in the range from ±10-308 to ±10308 with 15 or 16 decimal digits.

>> var = 1 + i ;

� char: 16-bit values, each representing a single characterThe char arrays are used to hold character strings.

>> comment = ‘This is a character string’ ;

The type of data assigned to a variable determines the type of variable that is created.

18

Initializing Variables in Assignment StatementsAn assignment statement has the general form

var = expression

Examples:>> var = 40 * i; >> a2 = [0 1+8];>> var2 = var / 5; >> b2 = [a2(2) 7 a];>> array = [1 2 3 4]; >> c2(2,3) = 5;>> x = 1; y = 2; >> d2 = [1 2];>> a = [3.4]; >> d2(4) = 4;>> b = [1.0 2.0 3.0 4.0];>> c = [1.0; 2.0; 3.0];>> d = [1, 2, 3; 4, 5, 6]; ‘;’ semicolon suppresses the>> e = [1, 2, 3 automatic echoing of values but

4, 5, 6]; it slows down the execution.

MATLAB BASICS

19

MATLAB BASICS

Initializing Variables in Assignment Statements

� Arrays are constructed using brackets and semicolons. All of the elements of an array are listed in row order.

� The values in each row are listed from left to right and they are separated by blank spaces or commas.

� The rows are separated by semicolons or new lines.

� The number of elements in every row of an array must be the same.

� The expressions used to initialize arrays can include algebraic operations and all or portions of previously defined arrays.

20

MATLAB BASICS

Initializing with Shortcut Expressions

first: increment: last• Colon operator: a shortcut notation used to initialize

arrays with thousands of elements

>> x = 1 : 2 : 10;>> angles = (0.01 : 0.01 : 1) * pi;

• Transpose operator: (′) swaps the rows and columns of an array

>> f = [1:4]′;>> g = 1:4; >> h = [ g′ g′ ];

1 12 23 34 4

h=

More on Vectors

x = start:end Creates row vector x starting with start, counting by 1, ending at end (provided end is an integer)

x = initial value : increment : final

value

Creates row vector x starting with start, counting by increment, ending at or before end

x = linspace(start,end,number) Creates linearly spaced row vector x starting with start, ending at end, having number elements

x = logspace(start,end,number) Creates logarithmically spaced row vector x starting with start, ending with end, having number elements

length(x) Returns the length of vector x

y = x’ Transpose of vector x

dot(x,y),cross(x,y) Returns the scalar dot and vector cross product of the vector x and y

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.

Initializing with Built-in Functions

zeros(n) Returns a n ⅹⅹⅹⅹ n matrix of zeros

zeros(m,n) Returns a m ⅹⅹⅹⅹ n matrix of zeros

rand(m,n) Returns a m ⅹⅹⅹⅹ n matrix of random numbers

eye(m,n) Returns a m ⅹⅹⅹⅹ n Identity matrix

ones(n) Returns a n ⅹⅹⅹⅹ n matrix of ones

ones(m,n) Returns a m ⅹⅹⅹⅹ n matrix of ones

size(A)For a m ⅹⅹⅹⅹ n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix

length(A) Returns the larger of the number of rows or columns in A

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.

26

32

54

7

6

1

10

8 9

11 12

4

7

1

10

2

5

Multidimensional Arrays

8

11

• A two dimensional array with m rows and n columns will occupy mxn successive locations in the computer’smemory. MATLAB always allocates array elements in column major order.

a= [1 2 3; 4 5 6; 7 8 9; 10 11 12];a(5) = a(1,2) = 2

• A 2x3x2 array of three dimensions

c(:, :, 1) = [1 2 3; 4 5 6 ];c(:, :, 2) = [7 8 9; 10 11 12];

Multidimensional Arrays

1 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

» A = Pascal(4);

» A(:,:,2) = magic(4)

A(:,:,1)

1 1 1 1

1 2 3 4

1 3 6 10

1 4 10 20

A(:,:,2)

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

» A(:,:,9) = diag(ones(1,4));

Page N

Page 10 0 0 0

0 0 0 0

0 0 0 0

0 0 0 0

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

1 1 1 1

1 2 3 4

1 3 6 10

1 4 10 20

>>A = 1;while length(A) < 4A = [0 A] + [A 0];end

28

• It is possible to select and use subsets of MATLAB arrays.

arr1 = [1.1 -2.2 3.3 -4.4 5.5];arr1(3) is 3.3arr1([1 4]) is the array [1.1 -4.4]arr1(1 : 2 : 5) is the array [1.1 3.3 5.5]

• For two-dimensional arrays, a colon can be used in a subscript to select all of the values of that subscript.

arr2 = [1 2 3; -2 -3 -4; 3 4 5];arr2(1, :)arr2(:, 1:2:3)

Sub arrays

29

• The end function: When used in an array subscript, it returns the highest value taken on by that subscript.

arr3 = [1 2 3 4 5 6 7 8];arr3(5:end) is the array [5 6 7 8]arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];arr4(2:end, 2:end)

• Using subarrays on the left hand-side of an assignment statement:

arr4(1:2, [1 4]) = [20 21; 22 23];(1,1) (1,4) (2,1) and (2,4) are updated.arr4 = [20 21; 22 23]; all of the array is changed.

Sub arrays (Contd.)

30

• Assigning a Scalar to a Sub array: A scalar value on the right-hand side of an assignment statement is copied into every element specified on the left-hand side.

>> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];>> arr4(1:2, 1:2) = 1arr4 =

1 1 3 41 1 7 89 10 11 12

Sub arrays (Contd.)

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 51 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])

• Use () parentheses to specify index• colon operator (:) specifies range / ALL• [ ] to create matrix of index subscripts• ‘end’ specifies maximum index value

A(1:end,end) A(:,end)A(21:end) ’

32

Hierarchy of operations

• x = 3 * 2 + 6 / 2• Processing order of operations is important

– parentheses (starting from the innermost)– exponentials (from left to right)– multiplications and divisions (from left to right)– additions and subtractions (from left to right)

>> x = 3 * 2 + 6 / 2x =

9

33

• MATLAB includes a number of predefined special values.These values can be used at any time without initializing them.

• These predefined values are stored in ordinary variables. They can be overwritten or modified by a user.

• If a new value is assigned to one of these variables, then that new value will replace the default one in all later calculations.

>> circ1 = 2 * pi * 10;>> pi = 3;>> circ2 = 2 * pi * 10;

Note: Never change the values of predefined variables.

Special Values

34

• pi: π value up to 15 significant digits• i, j: sqrt(-1)• Inf: infinity (such as division by 0)• NaN: Not-a-Number (division of zero by zero)• clock: current date and time in the form of a 6-element

row vector containing the year, month, day, hour, minute, and second

• date: current date as a string such as 15-Sept-2012• eps: epsilon is the smallest difference between two

numbers• ans: stores the result of an expression

Special Values (contd.)

Special Values (contd.)

� i and j are the imaginary numbers (can be overwritten)

>> i

ans = 0 + 1.0000i

� Exercise� Q -1: Execute the commands

a) exp(pi/2*i)

b) exp(pi/2i)

� Can you explain the difference between the two results?

Answer

Explanation –

a) exp(pi/2*i) = e (pi/2) *i = cos(pi/2) + i sin(pi/2)

b) exp(pi/2i) = e (pi/2i) = e (-pi/2)*i = cos(pi/2) –i sin(pi/2)

Note –A complex number 2+5i may be input as 2+5i or 2+5*i.In first case, i will be always interpreted as a complex number In second case, i is taken as complex only if i is not been assigned any local value.

b) exp(pi/2i) = 0.0000 - 1.0000 i

� a) exp(pi/2*i) = 0.0000 + 1.0000 i

37

• The input function displays a prompt string in the Command Window and then waits for the user to respond.

my_val = input( ‘Enter an input value: ’ );

in1 = input( ‘Enter data: ’ );

in2 = input( ‘Enter data: ’ ,`s`);

Initializing with Keyboard In put

MATLAB's output format or precision

>> help format� format Default. Same as SHORT. � format short Scaled fixed point format with 5 digits. � format long Scaled fixed point format with 15 digits. � format short e Floating point format with 5 digits. � format long e Floating point format with 15 digits. � format short g Best of fixed or floating point format with

5 digits.

� format long g Best of fixed or floating point format with 15 digits.

� format hex Hexadecimal format. � format rat Approximation by ratio of small integers.

39

>> value = 12.345678901234567;format short → 12.3457format long → 12.34567890123457format short e → 1.2346e+001format long e → 1.234567890123457e+001format short g → 12.346format long g → 12.3456789012346format rat → 1000/81

Changing the data format

Format Types (contd.)

� Matlab does not do exact arithmetic !

>> e = 1 - 3*(4/3 - 1)

e = 2.2204e-016

� >> cos(pi/2)

ans = 6.123233995736766e-017

String Arrays• Created using single quote delimiter (')

• Each character is a separate matrix element(16 bits of memory per character)

• Indexing same as for numeric arrays

» str = 'Hi there,'

str =

Hi there,

» str2 = 'Isn't MATLAB great?'

str2 =

Isn't MATLAB great?

1x9 vectorstr = H i t h e r e ,

42

MATLAB BASICS

The disp( array ) function>> disp( 'Hello' )Hello>> disp(5)

5>> disp( [ ' LNMIIT ' 'University' ] )LNMIIT University>> name = ‘ WORLD';>> disp( [ 'Hello ' name ] )Hello WORLD

43

MATLAB BASICS

The num2str() and int2str() functions>> d = [ num2str(14) ‘-March-' num2str(2013) ];>> disp(d)14-March-2013>> x = 23.11;>> disp( [ 'answer = ' num2str(x) ] )answer = 23.11>> disp( [ 'answer = ' int2str(x) ] )answer = 23

44

MATLAB BASICS

The fprintf( format, data ) function– %d integer– %f floating point format– %e exponential format– %g either floating point or exponential

format, whichever is shorter– \n new line character– \t tab character

45

MATLAB BASICS

>> fprintf( 'Result is %d', 3 )Result is 3>> fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 )Area of a circle with radius 3 is 28.274334>> x = 5;>> fprintf( 'x = %3d', x )x = 5>> x = pi;>> fprintf( 'x = %0.2f', x ) x = 3.14>> fprintf( 'x = %6.2f', x )x = 3.14>> fprintf( 'x = %d\ny = %d\n', 3, 13 )x = 3y = 13

46

MATLAB BASICS

Data files• save filename var1 var2 …

>> save myfile.mat x y → binary>> save myfile.dat x –ascii → ascii

• load filename>> load myfile.mat → binary>> load myfile.dat –ascii → ascii

Input / Output

48

Types of errors in MATLAB programs

• Syntax errors– Check spelling and punctuation

• Run-time errors– Check input data– Can remove “;” or add “disp” statements

• Logical errors– Use shorter statements– Check typos– Check units– Ask your friends, assistants, instructor, …

Matrix Functions

diag(A) – extract diagonal matrixtriu (A)– upper triangular matrixtril (A)– lower triangular matrixrand(m, n) – randomly generated matrixdet(A) – determinant of a matrixinv (A) – inverse of a matrixrank(A) – rank of a matrix

And some more matrix functions are available.

Eigenvalues and Eigenvectors :–eig– eigenvalues and eigenvectors

>>eig(A)produces a column vector with the eigenvalues and

>>[X,D]=eig(A)produces a diagonal matrix D with the eigenvalues onthe main diagonal, and a full matrix X whose columnsare the corresponding eigenvectors.

Built in functions

51

Operators (arithmetic)

– addition a + b → a + b– subtraction a - b → a - b– multiplication a x b → a * b– division a / b → a / b– exponent ab → a ^ b

Matrices Operations

Given A and B:

Addition Subtraction Product Transpose

Any MATLAB expression can be entered as a matrix element

Entering Numeric Arrays

» 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

Row separator:semicolon (;)

Column separator:space / comma (,)

Use square brackets [ ]

Entering Numeric Arrays (contd.)

» w=[1 2;3 4] + 5w =

6 78 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.45650.2311 0.4860 0.7621 0.0185

Scalar expansion

Creating sequencescolon operator (:)

Utility functions for creating matrices.

Operators (Element by Element)

.* element-by-element multiplication

./ element-by-element division

.^ element-by-element power

The use of “.” – “Element” Operation

K= x^2Erorr:??? Error using ==> mpower Matrix must be square.

B=x*yErorr:??? Error using ==> mtimes Inner matrix dimensions must agree.

A = [1 2 3; 5 1 4; 3 2 1]A =

1 2 35 1 43 2 -1

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

x = A(1,:)

x=1 2 3

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 43 4 6 83 6 4 89 12 12 165 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 [ ]

The resulting matrix must be rectangular.

4*a

Operations on Matrices

Transpose B=A’

Identity Matrixeye(n) -> returns an n X n identity matrix

eye(m,n) -> returns an m X n matrix with ones on the main diagonal and zeros elsewhere

Addition and Subtraction C =A +B C =A - B

Scalar Multiplication B = αA, where α is a scalar

Matrix Multiplication C = A * B

Matrix Inverse B = inv(A), A must be a square matrix in this case

Matrix powers B = A * A , A must be a square matrix

Determinant det(A), A must be a square matrix

Other elementary functions

Remarks

abs(x)angle(x)sqrt(x)real(x)imag(x)conj(x)round(x)fix(x)floor(x)ceil(x)sign(x)exp(x)log(x)log10(x)factor(x)sin, cos, tanasin, acos, atanmax, minmod, rem

Absolute value of xPhase angle of complex value: If x = real, angle = 0. If x =√-1, angle = pi/2Square root of xReal part of complex value xImaginary part of complex value xComplex conjugate xRound to do nearest integerRound a real value toward zeroRound x toward -∞Round x toward +∞+1 if x > 0; -1 if x < 0Exponential base eLog base eLog base 101 if x is a prime number, 0 if not

Mathematical Functions

And there are many more !

MATLAB Arithmetic OperatorsOperator Description

+ Addition

- Subtraction

.* Multiplication (element wise)

./ Right division (element wise)

.\ Left division (element wise)

= Assignment operator,e.g. a = b,(assign b to a)

: Colon operator (Specify Range )

....^ Power (element wise)

' Transpose

* Matrix multiplication

/ Matrix right division

\ Matrix left division

; Row separator in a Matrix

^ Matrix power

Basic Task: Plot the function

sin(x) between 0≤x≤4π� Create an x-array of 100 samples between 0

and 4π.

� Calculate sin(.) of the x-array

� Plot the y-array

>>x=linspace(0,4*pi,100);

>>y=sin(x);

>>plot(y)0 10 20 30 40 50 60 70 80 90 100

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

Plot the function e-x/3sin(x) between 0≤x≤4π

� Create an x-array of 100 samples between 0 and 4π.

� Calculate sin(.) of the x-array

� Calculate e-x/3 of the x-array

� Multiply the arrays y and y1

>>x=linspace(0,4*pi,100);

>>y=sin(x);

>>y1=exp(-x/3);

>>y2=y*y1;

Plot the function e-x/3sin(x) between

0≤x≤4π� Multiply the arrays y and y1 correctly

� Plot the y2-array

>>y2=y.*y1;

>>plot(y2)

0 10 20 30 40 50 60 70 80 90 100-0.3

-0.2

-0.1

0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

Display Facilities

� plot(.)

� stem(.)

Example:>>x=linspace(0,4*pi,100);>>y=sin(x);>>plot(y)>>plot(x,y)

Example:>>stem(y)>>stem(x,y)

0 10 20 30 40 50 60 70 80 90 100-0.3

-0.2

-0.1

0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0 10 20 30 40 50 60 70 80 90 100-0.3

-0.2

-0.1

0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

Plotting in MATLAB• Specify x-data and/or y-data• Specify color, line style and marker

symbol

• Syntax: 2-D Plotting– Plotting single line:

– Plotting multiple lines:

plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)

plot(xdata, ydata, 'color_linestyle_marker')

2-D Plotting - example

Create a Blue(default

color)Sine Wave

» x = 0:1:2*pi;

» y = sin(x);

» plot(x,y);

The parametric equation of a unit circle:x = cos ϴ and y = sin ϴ, 0≤ ϴ ≤ 2∏

>> theta = linspace (0, 2*pi, 100); %linearly spaced

>> x = cos (theta);

>> y = sin (theta);% calculate x and y coordinates

>> plot (x, y); % plot x vs y – plots an ellipse

>> axis (‘equal’); % set the length of both the axes same

>> xlabel (‘x’); % label the x-axis with x

>> ylabel (‘y’); % label the y-axis with y

>> title (‘Circle of unit radius’); % put a title on the plot

>> print % print on the default printer

Example

Plot

Note –axis, xlabel, ylabel and title commands are text strings. Text strings are entered within single quote.

-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x

y

-1 -0.5 0 0.5 1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

xy

Circle of unit radiusEllipse

Some more PlottingPlotting for visualization –

>> help plotIf x and y are two vector of the same length then plot(x,y) plots x versus y.

Example –>> x= -pi:0.01:pi;>> y = cos (x);>> plot(x, y, ‘r.’); %A new window opens and draws the graph%

% in red color%>> grid on %places grid lines to the current axis%>> zoom on>> xlabel (‘x:-pi to pi’);>> ylabel (‘sin (x)’);

-4 -3 -2 -1 0 1 2 3 4-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x:-pi to pi

sin(

x)

Graph of sin from –pi to pi

2-D Plotting : example-contd.

• GRID ON creates a grid on the current figure

• GRID OFF turns off the grid from the current figure

» x = 0:1:2*pi;

» y = sin(x);

» plot(x,y); grid on ;

Adding a Grid

y yellow . Pointm megenta o circlec cyan x x-markr red + plusg green - solid lineb blue * starw white : dottedk black -. dash dot

-- dashedExample –

>> plot(x, y, ’g *’);

Various line types, plot symbols and colors can be used in the plotting –

Multiple Graphs on One Plot

� Built-in function hold >> p1 = plot(t, z, 'r-') >> hold on >> p2 = plot(t, -z, 'b--') >> hold on >> p3 = plot(T, Z, 'go') >> hold off

For Comparison –

Multiple plots can be drawn on the same graph one above the other.by using –

>> plot(x, y, ‘r.’);>> hold on %Hold the above figure%>> plot(x, z, ‘b.’);>> hold off %Hold off from the above figure%

When multiple curves appear on the same axis, then create legendlabels and distinguish them.

>> legend(‘cos(x)’, ‘sin(x)’);

>> print %To obtain a hard copy of the current plot%

Multiple Plots on the same Graph

-4 -3 -2 -1 0 1 2 3 4-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

cos(x)

sin(x)

Multiple Plots on the same Figure

legend

Adding additional plots to a figure

• HOLD ON holds the current plot

• HOLD OFF releases hold on current plot

» x = 0:.1:2*pi;

» y = sin(x);

» plot(x,y,'b')

» grid on;

» hold on;

» plot(x,exp(-x),'r:*');

Controlling Viewing Area

• ZOOM ON allows user to select viewing area

• ZOOM OFF prevents zooming operations

• AXIS sets axis range[xmin xmax ymin ymax]

» axis([0 2*pi 0 1]);

Graph Annotation

TITLE

TEXTor

GTEXT

XLABEL

YLABEL

LEGEND

Display Facilities

� title(.)

� xlabel(.)

� ylabel(.)

>>title(‘This is the sinus function’)

>>xlabel(‘x (secs)’)

>>ylabel(‘sin(x)’)0 10 20 30 40 50 60 70 80 90 100

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1This is the sinus function

x (secs)si

n(x)

Subplots on One Figure

� Built-in function subplot >> s1 = subplot (1, 3, 1) >> p1 = plot (t, z, 'r-') >> s2 = subplot (1, 3, 2) >> p2 = plot (t, -z, 'b--') >> s3 = subplot (1, 3, 3) >> p3 = plot (T, Z, 'go')

Subplots (Contd.)SUBPLOT- display multiple axes in the same figure wi ndow

»subplot(2,2,1);

»plot(1:10);

»subplot(2,2,2);

»x = 0:.1:2*pi;

»plot(x,sin(x));

»subplot(2,2,3);

»x = 0:.1:2*pi;

»plot(x,exp(-x),’r’);

»subplot(2,2,4);

»plot(peaks);

subplot(#rows, #cols, index);

subplot– create an array of (titled) plots in the same window

surf– 3D shaded surface graph

mesh– 3D mesh surface

plot – plots in 2D space (x, y)

plot3– plots in 3D space (x, y, z)

clear %Erases all the variables from the memory%

quit %Exit from the program%

help %help for any existing MATLAB command%

help plot %will display the details about plotting%

Some more commands for data visualization

-3-2

-10

12

3

-2

0

2

-10

-5

0

5

Combination of Mesh and Contour

Example –%Produce a combination of mesh and contour plot %of the peaks surface%

>> [X,Y] = meshgrid(-3:.125:3); >> Z = peaks(X,Y);>> meshc(X,Y,Z); >> axis([-3 3 -3 3 -10 5])

PEAKS is a function of two variables, obtained by translating and scaling Gaussian distributions,which is useful for demonstratingMESH, SURF, PCOLOR, CONTOUR, etc.

MESHC(...) is the same as MESH(...)except that a contour plotis drawn beneath the mesh.

3-D Surface Plotting

Example:Advanced 3-D Plotting

» B = -0.2;

» x = 0:0.1:2*pi;

» y = -pi/2:0.1:pi/2;

» [x,y] = meshgrid(x,y);

» z = exp(B*x).*sin(x).*cos(y);

» surf(x,y,z)

Logical Operators

Operator Description& Returns 1 for every element location that is true (nonzero) in both arrays, and

0 for all other elements.

| Returns 1 for every element location that is true (nonzero) in either one or the other, or both, arrays and 0 for all other elements.

~ Complements each element of input array, A.

< Strictly Less than

<= Less than or equal to

> Strictly Greater than

>= Greater than or equal to

== Equal to

~= Not equal to

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

elseMatlab 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_ArrayMatlab Commands

end

Some Dummy Examples

for i=1:100Some Matlab Commands;

end

for j=1:3:200Some Matlab Commands;

end

for m=13:-0.2:-21Some 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)Matlab Commands

end

Dummy Example

while ((a>3) & (b==5))Some Matlab Commands;

end

M-File Programming

� Script M -Files o Automate a series of steps. o Share workspace with other scripts and the

command line interface. � Function M -Files o Extend the MATLAB language. o Can accept input arguments and return

output arguments. o Store variables in internal workspace.

A MATLAB Program

� Always has one script M-File � Uses built-in functions as well as new

functions defined in function M-files � Saved as <filename>.m

� To run: filename only (no .m extension) >> <filename> � Created in Editor / Debugger

M-File Editor / Debugger

� Create or open M-file in editor � >> edit <filename>.m� Type or copy commands� Use % for comments � Use ; to suppress output at runtime� Debugging mode

k >>

All the commands executed on MATLAB prompt can be written intoa file and saved with extension ‘*.m’ . This is called script file or M-file.

Example –‘compute.m’This can be executed at any time by typing compute at the MATLABprompt.>> compute

We can edit the saved M-files, by using MATLAB editor.>> edit compute.m

Other MATLAB files are –Function file, Mat file (*.mat) and Mex file (*.mex)

Example –>> R = 5;>> [x, y] = circlefn(R) ; % Executing a function file %

Script File

Script File – ‘circle.m’

% CIRCLE – A script file to draw a unit circle% ------------------------------------------------------close allclear allformat longtheta = linspace(0,2*pi,100); % create vector thetax = cos(theta); % generate x-coordinatesy = sin(theta); % generate y-coordinatesplot(x,y); % plot the circlesaxis(‘equal’); % set equal scale on axesxlabel (‘x’); % label the x-axis with xylabel (‘y’); % label the y-axis with ytitle(‘Circle of unit radius’) % put a title

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

If you include “;” at the end of each statement,result will not be shown immediately

Save file as Denem430.m

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

� 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

function out1=functionname(in1)function out1=functionname(in1,in2,in3)function [out1,out2]=functionname(in1,in2)

Writing User Defined Functions

� Examples� 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 keypause(3) %wait 3 seconds

Useful Commands

� The two commands used most by Matlabusers are

>>help functionname

>>lookfor keyword

103

Summary

• help command → Online help• lookfor keyword → Lists related commands• which → Version and location info• clear → Clears the workspace• clc → Clears the command window• diary filename → Sends output to file• diary on/off → Turns diary on/off• who, whos → Lists content of the workspace• more on/off → Enables/disables paged output• Ctrl+c → Aborts operation• … → Continuation• % → Comments

Questions ?

Thank You…

top related