Sei sulla pagina 1di 174

1

MATLAB
Lecture by
Sai Kumar Devulapalli

2
Contents
What is Matlab?

MATLAB Parts

MATLAB Desktop

Matrices
Numerical Arrays
String Arrays

Importing and Exporting Data

3
Contents
Graphics Fundamentals
2D plotting
Subplots
Specialized Plotting

Editing and Debugging M-files
Script and Function Files
Basic Parts of an M-file
Flow Control Statements
M-file Programming
4
Contents


Graphical User Interface (GUI)

Image Processing Examples

And many more .
5
Ground Rules
Listen
Participation
No Rank / Department
Breaks
Two way learning
6
Introduction of MATLAB

MATLAB is a program for doing numerical computation. It was
originally designed for solving linear algebra type problems using
matrices. Its name is derived from MATrix LABoratory.

MATLAB has since been expanded and now has several built-in
functions for solving problems required for data analysis, signal
processing, optimization, and several other types of scientific
computations.
It also contains functions for 2-D graphics , 3-D graphics and
animation.



7
What is Matlab?
Matlab is basically a high level language which has many
specialized toolboxes for making things easier for us

How high?

Assembly
High Level
Languages such as
C, Pascal etc.
Matlab
8
What is MATLAB?
High-performance software

Computation
Visualization
Easy-to-use environment.

High-level language

Data types
Functions
Control flow statements
Input/Output
Graphics
Object-oriented programming capabilities
9
MATLAB



Everything in MATLAB is a matrix !
10
MATLAB
The MATLAB is a command oriented environment somewhat
like UNIX.

A prompt appears on the screen and a MATLAB statement can
be entered.

When the <ENTER> key is pressed, the statement is executed,
and another prompt appears.

If a statement is terminated with a semicolon ( ; ), no results will
be displayed.

Otherwise results will appear before the next prompt.
11
What are we interested in?
Matlab is too broad for our purposes in this course.
The features we are going to look into are :


Matlab
Command
Line
m-files
functions
mat-files
Command execution
like DOS command
window
Series of
Matlab
commands
Input
Output
capability
Data
storage/
loading
12
MATLAB Parts
Developed Environment

Programming Language

Graphics

Toolboxes

Application Program Interface APIs
13
MATLAB Toolboxes
MATLAB has a number of add-on software modules or functions,
called toolbox , that perform more specialized computations to
solve problems of several applications. .

DSP Toolbox Signal Processing
Image Toolbox Image Processing
Wavelet Toolbox Wavelet Filter Design
Control Toolbox Control System
Communication Toolbox Communications
Etc

14
MATLAB Windows
MATLAB works through 3 basic windows in
almost all systems.

1. MATLAB Desktop

2. Figure Window

3. Editor Window

15
MATLAB Windows
16
The MATLAB Desktop
17
MATLAB Desktop Parts
Command Window

Command History

Workspace Browser

Current Directory

Help Browser

18
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

19
General Matlab Commands

clear Clears the workspace, all variables are removed

clear x y Clear variables x and y from work space

clc Clear the command window

close Closes last figures

clf clears figure window

clear all Clear all variables and functions from workspace

mlock fun locks function fun so that clear cannot remove it

munlock fun unlocks function fun so that clear can remove the
previously locked function

20
General Matlab Commands


who List the known or current variables

whos List current variables plus their size

what List all m-files in current directory

format Set output format

type test Display test.m in command window

delete test Delete test.m

which test Display directory path to closest test.m

21
General Matlab Commands
cd a : Change current working directory to a:

chdir a : Same as cd a:

dir List all files in the current directory

pwd Show current directory

ls Same as dir

path gets or sets the MATLAB path

editpath modifies MATLAB search path

copyfile copies a file

mkdir creates a directory


This we will work
later
22
General Matlab Commands
computer Tell you about the computer type you are using

clock gives you wall clock time and date as a vector

date tells you the date as a string

ver license and the complete MATLAB version info.

bench benchmarks your computer on running MATLAB
compared to other computers

Control c local abort; kills the curent command execution

quit quits MATLAB

exit same as quit


23
File Types in Matlab
MATLAB can read and write several types of files. However there are mainly 5 types
of files are there for storing data or programs.

1. M-Files : Standard ASCII text files with .m extension.
There are 2 types of m-files are there
1. Script files
2. Function files

All built-in-functions in MATLAB are M-files which are in precompiled format. Some
built-in-functions are provided with source code in readable M-files so that they can be
copied and modified.

Mat-Files : Binary data files with .mat extension

Fig-Files : Binary figure files with .fig extension

P-Files : These are compiled M-files with a .p extension

Mex-Files: MATLAB callable Fortran and C programs with a .mex extension to the
filename

24
Getting help
help List topics on which help is available

help topic Provides help on topic

lookfor string lookfor sqrt Search for keyword sqrt in m-files

helpdesk Opens the web-browser based help facility

helpwin command Opens the interactive help window

Demo Runs the demo program
25
MATLAB Variable Names
Variable names ARE case sensitive

Variable names can contain up to 63 characters (as of MATLAB
7.5)

Variable names must start with a letter followed by letters, digits,
and underscores.
26
MATLAB Special Variables
ans Default variable name for results

pi Value of

eps Smallest incremental number

inf Infinity

NaN Not a number

i and j i = j = square root of -1

realmin The smallest usable positive real number

realmax The largest usable positive real number
27
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;
28
Arithmetic Operators
+ addition

- subtraction

* multiplication

/ division

^ power

complex conjugate transpose

29
Math & Assignment Operators
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a


+ and are which operators ?

Addition + a + b
Subtraction - a - b
Assignment = a = b

30
MATLAB Relational Operators
MATLAB supports six relational operators.

Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
31
MATLAB Bitwise Operators

MATLAB supports 4 bitwise operators.

not ~

and &

or |

xor ^
32
MATLAB Logical Operators

MATLAB supports three logical operators.

not ~ % highest precedence
and && % equal precedence with or
or || % equal precedence with and
33
Other MATLAB symbols
>> prompt

. . . continue statement on next line

, separate statements and data

% start comment which ends at end of line

; (1) suppress output
(2) used as a row separator in a matrix

: specify range

34
Calculations at the Command Line
a = 2;
b = 5;
a^b

ans =
32
x = 5/2*pi;
y = sin(x)
y =
1
Results
assigned to
ans if name
not specified
Semicolon
suppresses
screen output
MATLAB as a calculator Assigning Variables
Note: Numbers stored in double-precision floating point format
-5/(4.8+5.32)^2
ans =
-0.0488
(3+4i)*(3-4i)
ans =
25
cos(pi/2)
ans =
6.1230e-017
35
Recap
36
MATRICES
37
Matrices
Entering and Generating Matrices

Subscripts

Scalar Expansion

Concatenation

Deleting Rows and Columns

Array Extraction

Matrix and Array Multiplication
38
MATLAB Matrices
MATLAB treats all variables as matrices.

For our purposes a matrix can be thought of as an array, in
fact, that is how it is stored.

Vectors are special forms of matrices and contain only one
row OR one column.

Scalars are matrices with only one row AND one column

39
MATLAB Matrices
A matrix with only one row AND one column is a scalar. A
scalar can be created in MATLAB as follows:

a_value=23

a_value =

23

40
MATLAB Matrices
A matrix with only one row is called a row vector. A row
vector can be created in MATLAB as follows (note the
commas):

rowvec = [12 , 14 , 63]

rowvec =

12 14 63

Column separator
space / comma (,)
41
MATLAB Matrices
A matrix with only one column is called a column vector.
A column vector can be created in MATLAB as follows
(note the semicolons):

colvec = [13 ; 45 ; -2]

colvec =

13
45
-2
Row separator
semicolon (;)
42
MATLAB Matrices
A matrix can be created in MATLAB as follows (note the
commas and semicolons):

matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

1 2 3
4 5 6
7 8 9
43
The Matrix in MATLAB
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1

2

Rows (m) 3

4

5
Columns
(n)
1 2 3 4 5
1 6 11 16 21



2 7 12 17 22



3 8 13 18 23



4 9 14 19 24



5 10 15 20 25
A =
A (2,4)
A (17)
Rectangular Matrix:
Scalar: 1-by-1 array
Vector: m-by-1 array
1-by-n array
Matrix: m-by-n array
44
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
Entering Numeric Arrays
Row separator
semicolon (;)

Column separator
space / comma (,)
Use square
brackets [ ]
45
w=[1 2;3 4] + 5
w =
6 7
8 9
x = 1:5
x =
1 2 3 4 5
y = 2:-0.5:0
y =
2.0000 1.5000 1.0000 0.5000 0
z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565
0.2311 0.4860 0.7621 0.0185
Scalar expansion
Creating sequences:
colon operator (:)
Utility functions for
creating matrices.
Entering Numeric Arrays
46
Scalar - Matrix Addition
a=3;
b=[1, 2, 3;4, 5, 6]
b =
1 2 3
4 5 6

c= b + a % Add a to each element of b
c =
4 5 6
7 8 9

47
Scalar - Matrix Subtraction
a=3;
b=[1, 2, 3;4, 5, 6]
b =
1 2 3
4 5 6

c = b - a %Subtract a from each element of b
c =
-2 -1 0
1 2 3
48
Scalar - Matrix Multiplication
a=3;
b=[1, 2, 3; 4, 5, 6]
b =
1 2 3
4 5 6

c = a * b % Multiply each element of b by a
c =
3 6 9
12 15 18
49
Scalar - Matrix Division
a=3;
b=[1, 2, 3; 4, 5, 6]
b =
1 2 3
4 5 6

c = b / a % Divide each element of b by a
c =
0.3333 0.6667 1.0000
1.3333 1.6667 2.0000
50
Array, Matrix Transpose
Matrix transpose: 'apostrophe

a vector x = [1 2 5 1]

x = 1 2 5 1


Transpose: y = x y = 1
2
5
1

51
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


x = ?

x = 1 2 3 4
5 6 7 8


52
Vector and Matrix Operations
+,-,*,/ are used in operations between matrices

.*,./,.^ are used in operations between matrix elements

Pay attention to the dimensions of vectors and matrices
53
Matrices Operations
Given A and B:
Addition Subtraction
Product
Transpose
54
Operators (Element by Element)


.* element-by-element multiplication

./ element-by-element division

.^ element-by-element power

55

The use of . Element Operation


Given A:
Divide each element of
A by 2
Multiply each
element of A by 3
Square each
element of A
56
Matrix Multiplication
a = [1 2 3 4; 5 6 7 8];
b = ones(4,3);
c = a*b
c =
10 10 10
26 26 26
[2x4]
[4x3]
[2x4]*[4x3] [2x3]
a(2nd row).b(3rd column)
a = [1 2 3 4; 5 6 7 8];
b = [1:4; 1:4];
c = a.*b
c =
1 4 9 16
5 12 21 32
c(2,4) = a(2,4)*b(2,4)
Array Multiplication
57
Array Subscripting / Indexing
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1

2

3

4

5
1 2 3 4 5
1 6 11 16 21



2 7 12 17 22



3 8 13 18 23



4 9 14 19 24



5 10 15 20 25
A =
A(3,1)
A(3)
A(1:5,5)
A(:,5)
A(21:25)
A(4:5,2:3)

A(1:end,end)
A(:,end)
A(21:end)
58
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.
59
Extracting a Sub-Matrix
A portion of a matrix can be extracted and stored in a
smaller matrix by specifying the names of both matrices
and the rows and columns to extract. The syntax is:

sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

where r1 and r2 specify the beginning and ending rows
and c1 and c2 specify the beginning and ending columns
to be extracted to make the new matrix.
60
MATLAB Matrices
A column vector can be
extracted from a matrix.
As an example we create a
matrix below:

matrix=[1,2,3;4,5,6;7,8,9]

matrix =
1 2 3
4 5 6
7 8 9
Here we extract column 2
of the matrix and make a
column vector:


col_two=matrix( : , 2)

col_two =

2
5
8
61
MATLAB Matrices
A row vector can be
extracted from a matrix.
As an example we create
a matrix below:

matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 3
4 5 6
7 8 9
Here we extract row 2 of
the matrix and make a
row vector. Note that the
2:2 specifies the second
row and the 1:3 specifies
which columns of the row.

rowvec=matrix(2 : 2 , 1 : 3)

rowvec =

62
Deleting Rows and Columns
A=[1 5 9;4 3 2.5; 0.1 10 3i+1]
A =
1.0000 5.0000 9.0000
4.0000 3.0000 2.5000
0.1000 10.0000 1.0000+3.0000i

A(:,2)
5.0000
3.0000
10.0000

63
Deleting Rows and Columns
A=[1 5 9;4 3 2.5; 0.1 10 3i+1]
A =
1.0000 5.0000 9.0000
4.0000 3.0000 2.5000
0.1000 10.0000 1.0000+3.0000i

A(:,2)=[]
A =
1.0000 9.0000
4.0000 2.5000
0.1000 1.0000 + 3.0000i

A(2,2)=[]
??? Indexed empty matrix assignment is not allowed.Dimension
mismatch
64
Recap
65
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 =

x = [1 2], y = [4 5],
z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2
4 5
Use square
brackets [ ]
Note: The resulting matrix must be rectangular
66
Numerical Array Concatenation
a=[1 2;3 4]
a =
1 2
3 4
cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
x = [1 2], y = [4 5],
z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2
4 5
Use square
brackets [ ]
Note: The resulting matrix must be rectangular
4*a
67
Generating Vectors from Utility 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
68
Matrix Manipulation Functions
zeros: Create an array of all zeros
ones: Create an array of all ones
eye: Identity Matrix
rand: Uniformly distributed random numbers
size: Return array dimensions
fliplr: Flip matrices left-right
flipud: Flip matrices up and down

69
Matrix Manipulation Functions
transpose (): Transpose matrix
rot90: rotate matrix 90
tril: Lower triangular part of a matrix
triu: Upper triangular part of a matrix
cross: Vector cross product
dot: Vector dot product
det: Matrix determinant
inv: Matrix inverse ---
eig: Evaluate eigenvalues and eigenvectors
rank: Rank of matrix

70
Character Arrays (Strings)
Created using single quote delimiter (')







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



Indexing same as for numeric arrays --- check
str = 'Hi there,'
str =
Hi there,
str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
1x9 vector
str = H i t h e r e
,
71
str ='Hi there,';
str1='Everyone!';
new_str=[str, ' ', str1];
new_str =
Hi there, Everyone!
str2 = 'Isn''t MATLAB great?';
new_str2=[new_str; str2]
new_str2 =
Hi there, Everyone!
Isn't MATLAB great?
1x19 vector
1x9 vectors
String Array Concatenation
Using [ ] operator:
Each row must be
same length

Row separator:
semicolon (;)

Column separator:
space / comma (,)
For strings of different length:
STRVCAT
char
new_str3 = strvcat(str, str2)
new_str3 =
Hi there,
Isn't MATLAB great?
2x19 matrix
2x19 matrix
(zero padded)
1x19 vectors
72
Working with String Arrays
String Comparisons

strcmp: compare whole strings
strncmp: compare first N characters
findstr: finds substring within a larger string
s = 'How much wood would a woodchuck
chuck?';

Converting between numeric & string arrays:

num2str: convert from numeric to string array
str2num: convert from string to numeric array
73
linspacings
y = linspace (Start,Stop,Npoints)
x = linspace (x1,x2,N) make sure N >=2
x=linspace(0,10,5)

y = linspace (x1,x2)
y = linspace (2,6)

Compute for equation of a straight line
74
Recap
75
M-File Programming
76
M-File
There are two kinds of M-files:
Scripts, which do not accept input arguments or
return output arguments. They operate on data in the
workspace.
Functions, which can accept input arguments and
return output arguments. Internal variables are local
to the function.
Click to create
a new M-File
77
A Script file
A script file is a user-created file with a sequence of
MATLAB commands in it. The file must be saved with a
.m extension to its name, thereby, making it an M-file.

A script file is executed by typing its name (without the .m
extension) at the command prompt.
78
Creating, Saving, and executing
a Script file
% CIRCLE A script file to draw a unit circle
% --------------

theta = linspace (2,10);
x= cos (theta);
y= sin (theta);
plot(x,y)
axis(equal);
xlabel(x)
ylabel(y)
title (circle of unit radius)
Now in MATLAB, type the following
commands:

Want to print the comments
Want symbol at centre
Circle

If the script file is open just press F5
to execute it
79
User Input of a Script file
% CIRCLE A script file to draw a unit circle
% --------------
r = input ( Enter the radius of the circle :);
theta = linspace ( 0.2 *pi ,100);
x= r * cos (theta);
y= r * sin (theta);
plot(x,y) % I want some symbol at the specified place
axis(equal);
xlabel(x)
ylabel(y)
title (circle of unit radius r)
80
Working with files & Directories
pwd
dir
mkdir sai
cd sai\
ls
x=1:100
y=log10(x)
save <filename> x y
ls

What

<filename>

cd ..

Pwd

ls
path
Dir

copyfile filename.m D:\D'ocuments and
Settings'\E440357\Desktop\O'ctober 07'\Sai\

ls
cd Sai\
81
Publishing Reports
Using built-in-publisher for publishing the reports
of MATLAB as attractive HTML or MS Word
document.

%% Publishing Reports A Simple Example
%% A curved Plot
% Let us plot a spiral given by
% r ( t ) = exp (-theta / 10 ) , 0 < theta <=10*pi

%% create vectors theta and r
theta = linspace(0,10*pi,200);
r=exp(-theta/10);

%% Now plot theta Vs r using a plot

plot (theta,r)

We can publish the reports in HTML, XML, WORD,
PPT etc
Publish ( filename, html)
Open html/filename.extension
82
More on Matrices
Q =
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30

>> v = [ 1 4 5]

>> Q(v,:);
>> Q(:, v);

>> Q(v,:)=[ ]
>> Q(:, v) = [ ]



83
More on Matrices
Q =
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30

>> v =[1 0 0 1 1];
>> v = logical(v);
>> Q(v,:)




84
Reshaping Matrices
As a vector : All the elements of a matrix A can be strung
into a single column vector by the command ---------

As a differently sized matrix : If matrix A is an m*n
matrix, it can be reshaped into a p * q matrix, as long as m
* n = p * q with the command reshape ( A, p, q)

Ex : if a is 6 * 6 matrix
Reshape (A, 9 ,4)
Reshape (A, 3 ,12) etc



85
Appending a row or column
A = 1 2 3
6 7 8
9 10 11

>> u =[1 0 0];
>> v = 9
0
21

A=[A;u]
A=[A v]
A=[A u]
A=[A u]





86
Continuation or Ellipsis
A = [ 1 3 9 ; 5 10 15 ; 0 0 -5];

A = [ 1 3 9
5 10 15
0 0 -5 ];

A = [ 1 3 9 ; 5 10 . . .
15 ; 0 0 -5 ];


87
Graphics Concepts
88
Graphics
Plotting
plot, title, xlabel, ylabel, grid, legend, hold, axis

Editing Plots

Subplots

Figures Property Editor

Handle Graphics

89
Plot
Plot (y) plots the columns of y versus their index

Plot (x,y) plots vector y versus vector x

Plot (x, y, s) plots vector y versus vector x, and s is a character
string which states the line properties

plot(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots
defined by the (X,Y,S) triples, where the X's and Y's are
vectors or matrices and the S's are strings.
90
Example Plots
Plot (y) plots the columns of y versus their index

x=[1 2 3 4] y=[1 2 7 9]

y=[7 19 21 98] y= [ 1 2 3; 4 5 6;7 8 9]


91
Color Options
Yellow - y

Magenta - m

Cyan - c

Red - r

Green - g

Blue - b

Black - k

92
Line Styles

- solid line (default)

-- dashed line

: dotted line

-. dash-dot line


93
Line Markings
+ - plus sign

o circle

* - asterisk

. Point

x cross

s square



Combined use of color, line style, and line marking : r+:

^ - upward pointing triangle

v - downward pointing triangle

- right pointing triangle

< - left pointing triangle

p - five-pointed star (pentagram)

h - six-pointed star (hexagram)

d - diamond

94
Example
1) t=0:0.1:4*pi; x=sin(t);
plot(x);
plot(t,x);
plot(t,x,r);
plot(t,x, 'c+:);
plot(t,x,'rh-.')

2) x=1:1:10; y=2*x;
plot(x,y,'r-');
95
Exercise
5 mins

Write a short program which plots 2 lines in a graph.
Two cycles of sin wave and cos wave.

Useful function: plot, sin, cos
Plot(x,y)-----------------------------plot(x,y,0,0,+)

96
Recap
97
Grid
Grid or GRID ON adds major grid lines to the
current axes.

GRID OFF removes major and minor grid lines from
the current axes.
98
Comment Functions
xlabel('text') adds text beside the x-axis on the current axis

ylabel('text') adds text beside the y-axis on the current axis

title('text') adds text at the top of the current axis

legend(string1,string2,string3, ...) puts a legend on the current
plot using the specified strings as labels

text(x,y,'string') adds the text in the quotes to location (X,Y)
on the current axes
99
Try this Plot
100
2-D Plotting
Syntax:

Example:
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
plot(x,y,x,z,'linewidth',2)
title('Sample Plot','fontsize',14);
xlabel('X values','fontsize',14);
ylabel('Y values','fontsize',14);
legend('Y data','Z data')
grid on
101
Sample Plot
Title
Ylabel
Xlabel
Grid
Legend
102
Axis
axis Control axis scaling and appearance.

axis([xMin xMax yMin yMax]) sets scaling for the x- and y-axes
on the current plot.

axy = [xMin xMax yMin yMax] and axis(axy);

Axis off turns off all axis labeling, tick marks and background.

Axis on turns axis labeling, tick marks and background back on.
103
Creating and printing simple plots
theta = linspace ( 0.2 *pi ,100);
x= cos (theta);
y= sin (theta);
plot(x,y)
axis(equal); // try without this
xlabel(x)
ylabel(y)
title (circle of unit radius)
print
104
Output - 1
105
Output - 2
106
Creating and printing simple plots
x = 0 : .1 :20;
y = exp (0.1 * x) .* sin (x);
plot(x,y)
axis('equal');
xlabel('Time (t) in seconds')
ylabel('The response Amplitude in mm')
title ('A simple 2-D plot')

107
Output
108
Exercise

Write a short program which plots 2 lines in a graph. Two cycles
of sin wave and cos wave.

Use as many functions as you can: plot, sin, cos, grid, xlabel,
ylabel, grid, title, legend, text, axis
109
Plots and Graphs Cont
HOLD ON holds the current plot and all axis
properties so that subsequent graphing commands
add to the existing graph.

HOLD OFF returns to the default mode whereby
PLOT commands erase the previous plots and reset
all axis properties before drawing new plots.


110
Subplots
Syntax:
subplot(M ,N ,P)

subplot(M (rows),N (columns),P(index))
If we want to make a few plots and place the plots side by side (not overlay), use the
subplot command to design your layout.

This command requires 3 integer arguments.

Subplot divides the graphics window into M*N sub windows and puts the plot generated
by the next plotting command into the Pth window.

Where the sub windows are counted as row-wise

Thus, the command subplot(2,2,3) , plot(x,y) divides the graphics window into four sub
windows and plots y vs. x in the third sub window, which is the first sub window in the
second row

111
Subplots
Syntax:
subplot(2,2,1);


subplot(2,2,2)
...

subplot(2,2,3)
...

subplot(2,2,4)
...
subplot(rows,cols,index)
112
Hold
HOLD Hold current graph.
HOLD ON holds the current
plot and all axis properties so
that subsequent graphing
commands add to the existing
graph.
HOLD OFF returns to the
default mode
HOLD, by itself, toggles the
hold state.
...
hold on;
y2 = x + 2;
plot(x, y2, 'g+:');
Example
113
Subplot
SUBPLOT Create axes in tiled
positions.
SUBPLOT(m,n,p), or
SUBPLOT(mnp), breaks the Figure
window into an m-by-n matrix of
small axes
x = [-3 -2 -1 0 1 2 3];
y1 = (x.^2) -1;
% Plot y1 on the top
subplot(2,1,1);
plot(x, y1,'bo-.');
xlabel('x values');
ylabel('y values');
% Plot y2 on the bottom
subplot(2,1,2);
y2 = x + 2;
plot(x, y2, 'g+:');
Example
114
Figure
FIGURE Create figure window.
FIGURE, by itself, creates a
new figure window, and
returns its handle.
x = [-3 -2 -1 0 1 2 3];
y1 = (x.^2) -1;
% Plot y1 in the 1
st
Figure
plot(x, y1,'bo-.');
xlabel('x values');
ylabel('y values');
% Plot y2 in the 2
nd
Figure
figure
y2 = x + 2;
plot(x, y2, 'g+:');
Example
115
Overlay plots - gtext



gtext('Linear Approximation')
gtext('First 3 terms')
gtext('In Taylor series')


There are 3 different
ways of generating
overlay plots in
MATLAB; the plot, hold
and line command
116
1. Script files
2. Function files
3. Execution of function files
4. Continuation
5. loops
6. Branches and control flow
7. Break
8. Error
9. Return
Programming in MATLAB

117
Script files

r=input('enter r :')
a=[ 5 2*r r; 3 6 2*r-1; 2 r-1 3*r];
b=[2;3;5];
det_a=det(a)
x=a\b

% execution
=========
r=1;
118
A Function file
A function file is also an M-file, just like a script file,
except it has a function definition line on the top that
defines the input and output variable explicitly.

function[output variables] = function_name(input
variables);

119
Creating, Saving, and executing
a Function file
function [x,y] = circlefn(r) ;
% CIRCLE A script file to draw a unit circle
% --------------

theta = linspace ( 0.2 *pi ,100);
x= r * cos (theta);
y= r * sin (theta);
plot(x,y)
axis(equal);
xlabel(x)
ylabel(y)
title (circle of unit radius)
120
Function files

function[output variables] = function_name(input variables);
where as the function name should be same as the file name ( without
the .m extension)
if function name is projectile the file name should be projectile.m

Examples

Function Definition Line File name
------------------------------- ------------
function [ rho, H, F]=motion (x,y,t); motion.m
function [ theta]=angleTH(x,y); angleTH.m
function theta=THETA(x,y,z); THETA.m
function [ ] = circle(r); circle.m
function circle(r); circle.m
121
Flow Control
if
for
while
break
.
122
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


123
if-elseif-else

i=5; j=21;
if i > 5
k=i;
elseif (i>1) && (j==20)
k=5*i +j;
else
k=1;
end
124
if-elseif-else

avgmark = 55
if avgmark >= 75
disp('passed with distinction!')
elseif avgmark >= 60
disp('passed in first class')
elseif avgmark >= 45
disp('passed in 2nd class')
elseif avgmark >= 30
disp('passed in 3rd class')
else
disp('Fail, not passed')
end

125
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

126
for loop

The for loop repeats a group of statements a fixed, predetermined number of times. A
matching end delineates the statements:

for m=1:100
num = 1/(m+1)
end


It is a good idea to indent the loops for readability, especially when they are
nested:

m=2;n=3;
for i = 1:m
for j = 1:n
c = 1/(i+j);
end
end
127
Control Structures
While Loop Syntax

while (condition)
Matlab Commands
end


Dummy Example

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



128
While loop
The while loop repeats a group of statements an indefinite number of
times
under control of a logical condition. A matching end delineates the
statements.

Check this program

v=1; num=2; i=1;
while num < 10
v = [v; num];
i=i+1;
num=2^i;
end
v
129
switch and case


The switch statement executes groups of statements based on the value of a
variable or expression. The keywords case and otherwise delineate the groups.
Only the first

color=input('color=','s')
switch color
case 'red'
c = [1 0 0]
case 'green'
c = [0 1 0]
case 'blue'
c = [0 0 1]
otherwise
error('invalid choice of color')
end
130
Structures
There are 2 Ways to Create Structures

1 with Keyword struct, which takes pair of field names and their field
values

Other is Assign values to the Fields of a structure variable

The difference between structures and cell arrays is , individual data
elements are identified using string names called fields in structures. In
arrays it is indexes.

friend = struct('Name','Sai','Age',29,'Address','hyderabad')

Friend. Name=Sai
Friend(2).Name=Apple
131
Cell Arrays
Cell Array is a special type of array where dissimilar
kinds of data can be stored as its elements.

Being a special kind of array, each element of a cell
array can be accessed by using index of the
corresponding element.

friends={Sai,29,Hyderabad,24.3};

132
Saving And Loading Data
matlabs internal standard for saving and loading data is the
mat-file.
The save command saves all the variables in the workspace to
a disk file called matlab.mat:

A=1
B=2:20
C=hello
Save filename
Load filename.mat
Open filename.mat
133
Interactive inputs

1. Input
2. keyboard
3. Pause
4. Input / Output
5. Menus

134
Interactive input

The commands input, keyboard, menu, and pause can be used
inside a script or function file for interactive user inputs

input
***********
input('string')--------displays the text in the string and waits
for the user input

n=input('Largest square matrix size is:');
more = input('More simulations ? (Y/N','s');---- the 's' of the
command directs MATLAB to save the user input as a string.
135
Keyboard

The command keyboard inside a script or a function file returns control to the
keyboard at the point where the command occurs.

The execution of a script or a function is not terminated. The command window
prompt >> changes to k >> to show the special status.

At this point, you can check variables already computed, change their values, and
issue any valid matlab command

The control is returned to the function by typing the word RETURN on the k >>
prompt with the enter key.

This command is useful for debugging functions. sometimes in long computations
you may like to check the intermediate results, plot them and see if the computation
is headed in the right direction, and then let the execution continue.

keyboard

136
pause

The command pause temporarily halts the current process. It can be used with or without an optional
argument:

pause halts the current process and waits for the user to give a "go-ahead" signal. pressing any key
resumes the process

Example:

for i=1:3

date
pause
whos
end
137
Input / Output


MATLAB supports many standard c-language file i/o functions for
reading and writing binary and text files.

t=[51 84 ];

fid=fopen('apple.txt','w');
fprintf(fid,'Row Matrix \n');
fprintf(fid, '-------------- \n');
fprintf(fid,'1st Coulmn 2nd Column \n');
fprintf(fid, ' %d %d \n', t);
fclose(fid);


138
Menus

Menu('Menu Name', 'option 1', 'option2',...)

Creates an on-screen menu with the menu name and lists the options in
the menu.
k=menu('Choose a color','Red','Green','Blue')
if k==1
a=10
elseif k==2
a=20
else
a=30
end
139
Menus

r=10;
theta=linspace(0,2*pi,100);
r=r*ones(size(theta));
coord=menu('Circle plot','caretesian ','polar');
if coord==1
plot(r.*cos(theta),r.*sin(theta))
axis('square')
else
polar(theta,r);
end
140
Graphical User Interface
141
Graphical User Interface
A graphical user interface (GUI) is a user interface
built with graphical objects such as :

Static labels
Command Buttons
Text Boxes
Toggle/Push Buttons
Check Boxes
Radio Buttons
Popup Menus


List Boxes
Sliders
Different Dialog Boxes
Fonts
Colors
Interactive Inputs
Menus
142
Working with Static Labels & Command Buttons
143
Working with Static Labels & Command Buttons
x=rand;
x=floor (x*100);
set(handles.text2,'String',x);
144
Working with Text Boxes
145
Working with Text Boxes
function edit1_Callback(hObject, eventdata, handles)
x=str2num(get(hObject,'String'));
x=x*x;
str=sprintf('%d',x);
set(handles.edit2,'String',str);


146
Working with Toggle / Push Buttons
147
Working with Toggle/ Push Buttons
function togglebutton1_Callback(h, eventdata, handles,
varargin)
status = get (hObject, 'Value')
if status ==0
set(handles.togglebutton1,'String','Toggle OFF');
else
set(handles.togglebutton1,'String','Toggle ON');
end

148
Working with Check Boxes
149
Working with Check Boxes
% --- Executes on button press in checkbox1.
function checkbox1_Callback(h, eventdata, handles,varargin)
st=get(handles.checkbox1,'Value');
st1=get(handles.checkbox2,'Value');
if st==1 && st1==1
set(handles.text2,'String','Both tea and Coffee');
end
if st==1 && st1==0
set(handles.text2,'String','only Coffee');
end
if st==0 && st1==1
set(handles.text2,'String','only Tea');
end
if st==0 && st1==0
set(handles.text2,'String','Choose your option please');
end

150
Working with Check Boxes
% --- Executes on button press in checkbox2.
function checkbox2_Callback(h, eventdata, handles,varargin)
st=get(handles.checkbox1,'Value');
st1=get(handles.checkbox2,'Value');
if st==1 && st1==1
set(handles.text2,'String','Both tea and Coffee');
end
if st==1 && st1==0
set(handles.text2,'String','only Coffee');
end
if st==0 && st1==1
set(handles.text2,'String','only Tea');
end
if st==0 && st1==0
set(handles.text2,'String','Choose your option please');
end

151
Working with Radio Buttons
152
Working with Radio Buttons
function radiobutton1_Callback(h, eventdata, handles, varargin)

set(handles.text2,'String','Absolutely Right');
set(handles.radiobutton1, 'Value',1);
set(handles.radiobutton2, 'Value',0);
set(handles.radiobutton3, 'Value',0);

function radiobutton2_Callback(h, eventdata, handles, varargin)
set(handles.text2,'String','Wrong Answer');
set(handles.radiobutton1, 'Value',0);
set(handles.radiobutton2, 'Value',1);
set(handles.radiobutton3, 'Value',0);

function radiobutton3_Callback(h, eventdata, handles, varargin)
set(handles.text2,'String','Wrong Answer');
set(handles.radiobutton1, 'Value',0);
set(handles.radiobutton2, 'Value',0);
set(handles.radiobutton3, 'Value',1);

153
Working with Popup Menus
154
Working with Popup Menus
function varargout = popumenu1_Callback(h,eventdata,handles,varargin)

str=get(handles.popupmenu1,'String');
val=get(handles.popupmenu1,'Value');

val1=strcmp(str(val), 'Dr.Rajendra Prasad');

if val1
set(handles.text3,'String','Correct answer!');
else
set(handles.text3,'String','Incorrect answer');
end

155
Working with List boxes
156
Working with List boxes
function varargout =
listbox1_Callback(h,eventdata,handles,varargin)

st=get(gcf,SelectionType);

if st(1)==o
val=get(handles.listbox1,value);
str=get(handles.listbox1,String);
set(handles.text1,'String',str(val));
end

157
Working with Sliders

158
Working with Sliders
function varargout =
slider1_Callback(h,eventdata,handles,varargin)

v1=get(handles.slider1,Value);
set(handles.text1,'String',v1);

159
Working with Dialog Boxes
errfig = errordlg('You have made an Error!','User
Error');

warnfig = warndlg('Warning: Something''s not
right!', 'Warning');

helpfig = helpdlg('You need Help!');

msgfig = msgbox('This is a Message','Msg');


160
Working with single / multiple Input Dialog Box
Answers = inputdlg ('Type Something below');

Answers = inputdlg({'Q1: What Your Name?','Q2:
What is your Address?','Q3: What is your
age?'},'Questionnaire');



161
Working with Question Dialog Box
ret_string = questdlg('Are You Awake?','Click Your
Response');




162
Working with uigetfile and uiputfile Dialog Box
[filename, pathname] = uigetfile ('circlefn.m','Pick an
M-file');

[filename, pathname] = uiputfile ('circlefn.m','Pick
an M-file');


163
Working setting fonts and colors
text= 'my Font Box';
uisetfont(text);

myfig = figure();
uisetcolor(myfig)


164
Menus

Menu('Menu Name', 'option 1', 'option2',...)

Creates an on-screen menu with the menu name and lists the options in
the menu.
r=10;
theta=linspace(0,2*pi,100);
r=r*ones(size(theta));
coord=menu('Circle plot','caretesian ','polar');
if coord==1
plot(r.*cos(theta),r.*sin(theta))
axis('square')
else
polar(theta,r);
end
165
Image Processing
166
Blurring an Image
% To blur an image using a function psf.

I = imread('D:\wallpapers\BABY1.bmp');
figure; % This is for Blured Image
imshow(I);
title('Original Image');
LEN = 31;
THETA = 11;
PSF = fspecial('motion',LEN,THETA);
Blurred = imfilter(I,PSF);
figure;
imshow(Blurred);
title('Blurred Image');

167
De-Blurring An Image
%Deblurring with the Wiener Filter:

Actual = imread('peppers.png');
figure;imshow(Actual);title('Original Image');
LEN = 31;
THETA = 11;
PSF = fspecial('motion',LEN,THETA);
Blurred = imfilter(Actual,PSF);
figure; imshow(Blurred);title('Blurred Image');
wnr1 = deconvwnr(Blurred,PSF);
figure;imshow(wnr1);
title('Restored, True PSF');

168
Adding Noise to image
% Add Gaussian Noise to an image

I = imread('eight.tif');
J = imnoise(I, 'gaussian');
imshow(I);
Figure;
imshow(J);

169
Adding Noise to image Cont
% Add Salt & Pepper / Poisson / Speckle Noiseto an
image

I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.02');
%J = imnoise(I,'poisson')
%J = imnoise(I,'speckle',0.04)
imshow(I);
figure,
imshow(J);

170
Color to B/W
% To change the image from color to BW

I=imread('peppers.png');
imshow(I)
figure
BW = im2bw(I);
imshow(BW)


171
Resizing the Image
% To increases the size of the image

I = imread('circuit.tif');
J = imresize(I,1.25);
imshow(I)
figure
imshow(J)

172
Adding 2 Images / constant
%Add two images together and specifies an output class.

I = imread('rice.png');
J = imread('cameraman.tif');
K = imadd(I,J,'uint16');
imshow(K,[])
==============================

I = imread('rice.png');
J = imadd(I,50);
subplot(1,2,1), imshow(I)
subplot(1,2,2), imshow(J)




173
Matlab Vedios Link
http://www.mathworks.com/demos/matlab/getting-
started-with-matlab-video-tutorial.html
174
Thanks




Questions ??

Potrebbero piacerti anche