[go: up one dir, main page]

0% found this document useful (0 votes)
43 views105 pages

Basic-Matlab coursesa

oka

Uploaded by

Vaibhav Mali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views105 pages

Basic-Matlab coursesa

oka

Uploaded by

Vaibhav Mali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

MATLAB BASICS

Dr. Adigoppula Raju

Introduction to Computing in Science and Engineering


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-6

ans =
-1
 >> 7/8

ans =
0.8750
>> 9*2

ans =
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
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
arr(3,2)
Row 4

Col 1 Col 2 Col 3 Col 4 Col 5

8
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 and
matrices.

9
MATLAB BASICS
 Vector: Array with one dimension

 Matrix: Array with more than one dimension


 Size of an array is specified by the number of rows
and the number of columns, with the number of
rows mentioned first (For example: n x m array).
Total number of elements in an array is the
product of the number of rows and the number of
columns.

10
MATLAB BASICS
1 2
a= 3 4 3x2 matrix  6 elements
5 6

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

1
c= 3 3x1 array  3 elements, column vector
5

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

Row # Column #

11
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.

12
Variables
 No need for types. i.e.,

int a;
double b;
float c;

 All variables are created with double precision unless


specified and they are matrices.
Example:
>>x=5;
>>x1=2;

 After these statements, the variables are 1x1 matrices


with double precision
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/0 >> x = 1.e1000 >> x = log(0)


x= x= x=
Inf Inf Inf

 Other value NaN – not a number:

>> x = 0/0 >> x = inf/inf >> x = inf * 0


x= x= x=
NaN NaN NaN
MATLAB BASICS
Common types of MATLAB variables
 double: 64-bit double-precision floating-point numbers
They can hold real, imaginary 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 character
The 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.
17
MATLAB BASICS
Initializing Variables in Assignment Statements
An 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.

18
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.

19
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 1 1
>> f = [1:4]′; 2 2
h=
>> g = 1:4; 3 3
>> h = [ g′ g′ ]; 4 4
20
More on Vectors
x = start:end Creates row vector x starting with start, counting by 1,
ending at end
x = initial value : increment : final Creates row vector x starting with start, counting by
value 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

For a m ⅹ n matrix A, returns the row vector [m,n]


size(A)
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 x = zeros(1,3)
x =
0 0 0
 ones(M,N) MxN matrix of ones
x = ones(1,3)
x =
1 1 1
 rand(M,N) MxN matrix of uniformly
distributed random x = rand(1,3)
numbers on (0,1) 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.
Multidimensional Arrays
• A two dimensional array with m rows and n columns
will occupy mxn successive locations in the computer’s
memory. 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 1
4
• A 2x3x2 array of three dimensions 1 2 3 7
c(:, :, 1) = [1 2 3; 4 5 6 ]; 4 5 6 10
c(:, :, 2) = [7 8 9; 10 11 12]; 7 8 9 2
10 11 12 5
8
11

26
Multidimensional Arrays
>>A = 1;
while length(A) < 4
A = [0 A] + [A 0]; » A = Pascal(4);
end » A(:,:,2) = magic(4)
Page N A(:,:,1)
1 1 1 1
1 0 0 0
0 1 0 0
1 2 3 4
0 0 1 0 1 3 6 10
0 0 0 1 1 4 10 20
A(:,:,2)
0 0 0 0
16 2 3 13
Page 1 16 20 30 130 0
5 11 10 8
0 100 80 0
1 15 11
1 1 9 7 6 12
9 70 60 120 0
1 2 3 4 4 14 15 1
4 14 15 1
1 3 6 10 » A(:,:,9) = diag(ones(1,4));
1 4 10 20
Sub arrays

• 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.3
arr1([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)

28
Sub arrays (Contd.)

• 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.

29
Sub arrays (Contd.)

• 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) = 1
arr4 =
1 1 3 4
1 1 7 8
9 10 11 12

30
Array Subscripting / Indexing
1 2 3 4 5
A= 4
1
10 6 1
11
6
16
2
21

1
2 12 17

2
8 1.2 7 9 4 25 22
A(1:5,5) A(1:end,end)
3 7.2 3
5 8
7 13
1 18
11 23 A(:,5) A(:,end)
A(21:25) A(21:end)
A(3,1) 4 0 4
0.5 9 4 14
5 19
56 24
A(3) 5
5 23 83 10 13 15 0 20
10 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
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 / 2
x=
9

32
Special Values
• 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.

33
Special Values (contd.)
• 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 17-August-2016
• eps: epsilon is the smallest difference between two
numbers
• ans: stores the result of an expression

34
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
 a) exp(pi/2*i) = 0.0000 + 1.0000 i
b) exp(pi/2i) = 0.0000 - 1.0000 i

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.
Initializing with Keyboard Input

• 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`);

37
MATLAB's output format or precisio n
>> 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.
Changing the data format
>> value = 12.345678901234567;
format short  12.3457
format long  12.34567890123457
format short e  1.2346e+001
format long e  1.234567890123457e+001
format short g  12.346
format long g  12.3456789012346
format rat  1000/81

39
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 (')
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn't MATLAB great?'
str2 =
Isn't MATLAB great?

• Each character is a separate matrix


element
(16 bits of memory per character)

str = H i t h e r e , 1x9 vector

• Indexing same as for numeric arrays


MATLAB BASICS

The disp( array ) function


>> disp( 'Hello' )
Hello
>> disp(5)
5
>> disp( [ ‘DIAT' 'University' ] )
DIAT University
>> name = ‘Welcome Research Scholar';
>> disp( [ 'Hello ' name ] )
Hello Welcome Research Scholar

42
MATLAB BASICS

The num2str() and int2str() functions


>> d = [ num2str(17) ‘- August-' num2str(2016) ];
>> disp(d)
17-August-2016
>> x = 23.11;
>> disp( [ 'answer = ' num2str(x) ] )
answer = 23.11
>> disp( [ 'answer = ' int2str(x) ] )
answer = 23

43
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

44
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=3
y = 13
45
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

46
Input / Output
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, …

48
Matrix Functions
diag (A) – extract diagonal matrix
triu (A)– upper triangular matrix
tril (A)– lower triangular matrix
rand (m, n) – randomly generated matrix
det (A) – determinant of a matrix
inv (A) – inverse of a matrix
rank (A) – rank of a matrix

And some more matrix functions are available.


Built in functions
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 on
the main diagonal, and a full matrix X whose columns
are the corresponding eigenvectors.
Operators (arithmetic)

– addition a+b  a+b


– subtraction a-b  a-b
– multiplication axb  a*b
– division a/b  a/b
– exponent ab  a^b

51
Matrices Operations

Given A and B:

Addition Subtraction Product Transpose


Entering Numeric Arrays
Row separator: » a=[1 2;3 4]
semicolon (;)
a = Use square
Column separator:
1 2 brackets [ ]
space / comma (,) 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
Entering Numeric Arrays (contd.)

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


w =
6 7
8 9
» x = 1:5
Creating sequences
x =
colon operator (:)
1 2 3 4 5
» y = 2:-0.5:0
y =
2.0000 1.5000 1.0000 0.5000 0
Utility functions for » z = rand(2,4)
creating matrices. z =
0.9501 0.6068 0.8913 0.4565
0.2311 0.4860 0.7621 0.0185
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

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Numerical Array Concatenation - [ ]

Use [ ] to combine » a=[1 2;3 4]


existing arrays as a = Use square
matrix “elements” 1 2 brackets [ ]
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
Row separator:
cat_a =
semicolon (;) 1 2 2 4
3 4 6 8
Column separator: 3 6 4 8
9 12 12 16
4*a
space / comma (,)
5 10 6 12
15 20 18 24

The resulting
matrix must
be rectangular.
Operations on Matrices
Transpose B=A’

eye(n) -> returns an n X n identity matrix


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


Mathematical Functions
Other elementary Remarks
functions
abs(x) Absolute value of x
angle(x) Phase angle of complex value: If x = real, angle = 0. If x = √-1, angle = pi/2
sqrt(x) Square root of x
real(x) Real part of complex value x
imag(x) Imaginary part of complex value x
conj(x) Complex conjugate x
round(x) Round to do nearest integer
fix(x) Round a real value toward zero
floor(x) Round x toward - ∞
ceil(x) Round x toward + ∞
sign(x) +1 if x > 0; -1 if x < 0
exp(x) Exponential base e
log(x) Log base e
log10(x) Log base 10
factor(x) 1 if x is a prime number, 0 if not
sin, cos, tan
asin, acos, atan
max, min
mod, rem
And there are many more !
MATLAB Arithmetic Operators
Operator 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π.

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

 Calculate sin(.) of the x-array


1

0.8

0.6

>>y=sin(x); 0.4

0.2

Plot the y-array


0

 -0.2

-0.4

-0.6

>>plot(y) -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/3sin(x) between
0≤x≤4π
 Multiply the arrays y and y1 correctly
>>y2=y.*y1;

 Plot the y2-array


0.7

>>plot(y2) 0.6

0.5

0.4

0.3

0.2

0.1

-0.1

-0.2

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

0.6

 plot(.) 0.5

0.4

0.3

Example: 0.2

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

>>y=sin(x); 0

>>plot(y)
-0.1

-0.2
>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100

stem(.)
0.7

 0.6

0.5

0.4

0.3

Example:
0.2

0.1
>>stem(y) 0

>>stem(x,y) -0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Plotting in MATLAB
• Specify x-data and/or y-data
• Specify color, line style and marker
symbol

• Syntax: 2-D Plotting


– Plotting single line:
plot(xdata, ydata, 'color_linestyle_marker')

– Plotting multiple lines:


plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
2-D Plotting - example

Create a Blue
(default
color)
Sine Wave

» x = 0:1:2*pi;
» y = sin(x);
» plot(x,y);
Example
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
Plot
Ellipse Circle of unit radius
1

0.8 0.8

0.6 0.6

0.4 0.4

0.2 0.2

0 0
y

y
-0.2 -0.2

-0.4 -0.4

-0.6 -0.6

-0.8 -0.8

-1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 -1 -0.5 0 0.5 1
x x

Note – axis, xlabel, ylabel and title commands are text strings.
Text strings are entered within single quote.
Some more Plotting
Plotting for visualization –
>> help plot
If 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)’);
Graph of sin from –pi to pi
1

0.8

0.6

0.4

0.2
sin(x

0
)

-0.2

-0.4

-0.6

-0.8

-1
-4 -3 -2 -1 0 1 2 3 4
x:-pi t o pi
2-D Plotting : example-contd.

Adding a Grid

• 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;
Various line types, plot symbols and colors
can be used in the plotting –
y yellow . Point
m megenta o circle
c cyan x x-mark
r red + plus
g green - solid line
b blue * star
w white : dotted
k black -. dash dot
-- dashed
Example –
>> plot(x, y, ’g *’);
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
Multiple Plots on the same Graph

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 legend
labels and distinguish them.
>> legend(‘cos(x)’, ‘sin(x)’);

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


Multiple Plots on the same Figure
1
c o s ( x)
0.8 sin(x)
legend
0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
-4 -3 -2 -1 0 1 2 3 4
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 LEGEND

TEXT
or
GTEXT
YLABEL

XLABEL
Display Facilities

 title(.)
>>title(‘This is the sinus function’)
This is the sinus function
1

0.8

 xlabel(.) 0.6

0.4

>>xlabel(‘x (secs)’) 0.2

sin(x)
0

 ylabel(.) -0.2

-0.4

-0.6

-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
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 window
subplot(#rows, #cols, index);
»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);
Some more commands for data visualization
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%


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])
5
PEAKS is a function of two
variables, obtained by translating
and scaling Gaussian distributions, 0
which is useful for demonstrating
MESH, SURF, PCOLOR, -5

CONTOUR, etc.
-1 0

MESHC(...) is the same as MESH(.2..) 2


3

except that a contour plot 0


0
1

is drawn beneath the mesh. -2 -2


-1

-3
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
Some Dummy Examples
 If Statement Syntax
if ((a>3) & (b==5))
Some Matlab Commands;
if (Condition_1) end
Matlab Commands
if (a<3)
elseif (Condition_2) Some Matlab Commands;
Matlab Commands elseif (b~=5)
Some Matlab Commands;
elseif (Condition_3) end
Matlab Commands
if (a<3)
else Some Matlab Commands;
Matlab Commands else
end Some Matlab Commands;
end
Control Structures
Some Dummy Examples
 For loop syntax for i=1:100
Some Matlab Commands;
end

for i=Index_Array for j=1:3:200


Some Matlab Commands;
Matlab Commands end

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

Dummy Example
while (condition)
Matlab Commands while ((a>3) & (b==5))
Some Matlab Commands;
end 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 >>
Script File
All the commands executed on MATLAB prompt can be written into
a 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 MATLAB
prompt.
>> 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 – ‘circle.m’
% CIRCLE – A script file to draw a unit circle
%
close all
clear all
format long
theta = linspace(0,2*pi,100); % create vector theta
x = cos(theta); % generate x-coordinates
y = sin(theta); % generate y-coordinates
plot(x,y); % plot the circles
axis(‘equal’); % set equal scale on axes
xlabel (‘x’); % label the x-axis with x
ylabel (‘y’); % label the y-axis with y
title(‘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 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
 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
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

103
Questions ?
Thank You…

You might also like