Top Banner
MATLAB An Introduction Krishna K. Mohbey 1 NIT Bhopal
122
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: MATLAB INTRODUCTION

MATLAB

An Introduction

Krishna K. Mohbey

1 NIT Bhopal

Page 2: MATLAB INTRODUCTION

INTRODUCTION TO MATLAB

MATLAB stands for MATrix LABoratory.

What is MATLAB?

MATLAB provides a language and environment for numerical computation, data analysis,visualisation and algorithm development

MATLAB provides functions that operate on

Integer, real and complex numbers

Vectors and matrices

Structures

2

Page 3: MATLAB INTRODUCTION

MATLAB FUNCTIONALITY

Built-in Functionality includes Matrix manipulation and linear algebra

Data analysis

Graphics and visualisation

…and hundreds of other functions

Add-on toolboxes include Image processing

Signal Processing

Optimization

Genetic Algorithms

…and many more toolboxes

Page 4: MATLAB INTRODUCTION

Typical uses include: • Math and computation

• Algorithm development

• Modelling, simulation, and prototyping

• Data analysis, exploration, and visualization

• Scientific and engineering graphics

• Application development, including Graphical User Interface

building

4

MATLAB

Page 5: MATLAB INTRODUCTION

A good choice for vision program development because:

• Easy to Use

• Quick to learn,

• Good documentation

• A Big library for functions

• Excellent display capabilities

• Widely used for teaching and research in universities and industry

5

Why MATLAB

Page 6: MATLAB INTRODUCTION

MATLAB consists :

• The MATLAB language • A high-level matrix/array language with control flow statements, functions,

data structures, input/output, and object-oriented programming features. • The MATLAB working environment • The set of tools and facilities that you work with as the MATLAB user or

programmer, including tools for developing, managing, debugging, and profiling

• Handle Graphics • It includes high-level commands for two-dimensional and three-

dimensional data visualization, image processing, animation, and presentation graphics.

• …(cont’d)

6

MATLAB Components

Page 7: MATLAB INTRODUCTION

• MATLAB function library. • A vast collection of functions like sum, sine, cosine, and complex

arithmetic, to more sophisticated functions like matrix inverse, matrix Eigen values, Bessel functions, and fast Fourier transforms as well as special image processing related functions

• The MATLAB Application Program Interface (API) • A library that allows you to write C and Fortran programs that interact with

MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

7

MATLAB Components

Page 8: MATLAB INTRODUCTION

Some facts for a first impression • MATLAB is an interpreted language, no compilation needed

• MATLAB does not need any variable declarations, no dimension

statements, no packaging, no storage allocation, no pointers

• Programs can be run step by step, with full access to all variables,

functions etc.

8

MATLAB

Page 9: MATLAB INTRODUCTION

MATLAB has an interactive environment

Commands are interpreted one line at a time

Commands may be scripted to create your own functions or procedures

Variables are created when they are used

Variables are typed, but variable names may be reused for different types

MATLAB

Page 10: MATLAB INTRODUCTION

Connecting to MATLAB

Excel / COM

File I/O

C/C++ Java Perl

10

Page 11: MATLAB INTRODUCTION

Excel COM

Deploying with MATLAB

11

Page 12: MATLAB INTRODUCTION

MATLAB Toolboxes

MATLAB has a number of add-on software modules, called toolbox , that perform more specialized computations.

12

Page 13: MATLAB INTRODUCTION

MATLAB Toolboxes

Statistics Toolbox

Optimization Toolbox

Database Toolbox

Parallel Computing Toolbox

Image Processing Toolbox

Bioinformatics Toolbox

Fuzzy Logic Toolbox

Neural Network Toolbox

Data Acquisition Toolbox

MATLAB Report Generator

Signal Processing Communications System Identification Wavelet Filter Design Control System Robust Control

13

Page 14: MATLAB INTRODUCTION

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

14

Page 15: MATLAB INTRODUCTION

WINDOW COMPONENTS

Command Prompt – MATLAB commands are entered here.

Workspace – Displays any variables created (Matrices, Vectors,

Singles, etc.)

Command History - Lists all commands previously entered.

Double clicking on a variable in the Workspace will open an Array Editor.

This will give you an Excel-like

view of your data.

15

Page 16: MATLAB INTRODUCTION

MATLAB Help

• MATLAB Help is an extremely powerful assistance to learning MATLAB

• Help not only contains the theoretical background, but also shows demos for implementation

• MATLAB Help can be opened by using the HELP pull-down menu

16

Page 17: MATLAB INTRODUCTION

MATLAB Help (cont.)

• Any command description can

be found by typing the command in the search field

• As shown above, the command to take square root

(sqrt) is searched

• We can also utilize MATLAB Help from the command

window as shown

17

Page 18: MATLAB INTRODUCTION

STARTING AND STOPPING MATLAB

To Start

select

Start->Programs->MATLAB R2007a

OR

To get started, type one of these commands:

helpwin, helpdesk, or demo

To stop (nicely)

Select File -> Exit MATLAB

Or

type quit in the MATLAB command window

Page 19: MATLAB INTRODUCTION

MATLAB Special Variables

1. ans Default variable name for results

2. pi Value of

3. eps Smallest incremental number

4. inf Infinity

5. NaN Not a number e.g. 0/0

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

7. realmin The smallest usable positive real number

8. realmax The largest usable positive real number

19

Page 20: MATLAB INTRODUCTION

Some Useful MATLAB commands

who List known variables

whos List known variables plus their size

help >> help sqrt Help on using sqrt

lookfor >> lookfor sqrt Search for

keyword sqrt in m-files

what >> what a: List MATLAB files in a:

clear Clear all variables from work space

clear x y Clear variables x and y from work space

clc Clear the command window

20

Page 21: MATLAB INTRODUCTION

Some Useful MATLAB commands

what List all m-files in current directory

dir List all files in current directory

ls Same as dir

type test Display test.m in command window

delete test Delete test.m

cd a: Change directory to a:

chdir a: Same as cd

pwd Show current directory

which test Display directory path to ‘closest’ test.m

21

Page 22: MATLAB INTRODUCTION

To clear a variable

» who

Your variables are:

D ans rho NRe mu v

» clear D » who

Your variables are:

NRe ans mu rho v

» 22

Page 23: MATLAB INTRODUCTION

To clear variables

» who

Your variables are:

NRe ans mu rho v

» clear » who »

23

Page 24: MATLAB INTRODUCTION

Complex Numbers

» i ans = 0 + 1.0000i » c1 = 2+3i c1 = 2.0000 + 3.0000i »

24

Page 25: MATLAB INTRODUCTION

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

25

Page 26: MATLAB INTRODUCTION

MATLAB Arithmetic Operators

- (unary) + (unary)

1. Addition + a + b 2. Subtraction - a - b

3. Multiplication * or .* a*b or a.*b

4. Division / or ./ a/b or a./b 5. or \ or .\ b\a or b.\a

6. Assignment = a = b (assign b to a)

26

Page 27: MATLAB INTRODUCTION

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 ~=

27

Page 28: MATLAB INTRODUCTION

MATLAB Logical Operators

MATLAB supports three logical operators.

not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and

Power Operators

Power ^ or .^

a^b or a.^b

28

Page 29: MATLAB INTRODUCTION

VARIABLES, VECTORS AND MATRICES Variables Names

Variable names must start with a letter followed by letters, digits, and

underscores.

Reserved names are IF, WHILE, ELSE, END, SUM, etc.

Variable names ARE case sensitive

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

and newer)

Variables Value

This is the data the is associated to the variable; the data is accessed by using the name.

29

Page 30: MATLAB INTRODUCTION

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;

30

Page 31: MATLAB INTRODUCTION

SINGLE VALUES

Singletons

To assign a value to a variable use the equal symbol ‘=‘ >> A = 32

To find out the value of a variable simply type the name in

31

Page 32: MATLAB INTRODUCTION

SINGLE VALUES

To make another variable equal to one

already entered

>> B = A

The new variable is not updated as you

change the original value

Note: using ; suppresses output

32

Page 33: MATLAB INTRODUCTION

SINGLE VALUES

The value of two variables can be added together, and the result displayed… >> A = 10

>> A + A

…or the result can be stored in another variable

>> A = 10

>> B = A + A

33

Page 34: MATLAB INTRODUCTION

VECTORS

A vector is a list of numbers Use square brackets [] to contain the numbers

To create a row vector use ‘,’ to separate the content

34

Page 35: MATLAB INTRODUCTION

A Column Vector

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

35

Page 36: MATLAB INTRODUCTION

Column Vectors

To create a column vector use ‘;’ to separate the content

36

Page 37: MATLAB INTRODUCTION

A Row Vector

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

37

Page 38: MATLAB INTRODUCTION

VECTORS

A row vector can be converted into a column vector by using the transpose operator ‘

38

Page 39: MATLAB INTRODUCTION

MATRICES

You can create matrices (arrays) of any size using a combination of the methods for creating vectors

List the numbers using ‘,’ to separate each column and then ‘;’ to define a new row

39

Page 40: MATLAB INTRODUCTION

MATRICES

You can also use built in functions to create a matrix >> A = zeros(2, 4)

creates a matrix called A with 2 rows and 4 columns containing the value 0

>> A = zeros(5) or >> A = zeros(5, 5)

creates a matrix called A with 5 rows and 5 columns

You can also use: >> ones(rows, columns)

>> rand(rows, columns)

Note: MATLAB always refers to the first value as the number of Rows then the second as the number of Columns

40

Page 41: MATLAB INTRODUCTION

A Scalar

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

» x=23

x =

23

41

Page 42: MATLAB INTRODUCTION

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

42

Page 43: MATLAB INTRODUCTION

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.

43

Page 44: MATLAB INTRODUCTION

MATLAB Matrices

A column vector can be extracted from a matrix. As an example we create a matrix below:

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

m =

1 2 3

4 5 6

7 8 9

Here we extract column 2 of the matrix and make a column vector:

» coltwo=m( : , 2)

coltwo =

2

5

8

44

Page 45: MATLAB INTRODUCTION

MATLAB Matrices

A row vector can be extracted from a matrix. As an example we create a matrix below:

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

mat =

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=mat (2 : 2 , 1 : 3)

rowvec =

4 5 6

45

Page 46: MATLAB INTRODUCTION

Special Matrices

1111

1111ones(2,4)

111

111

111

)3(

00

00

00

zeros(3,2)

100

010

001

)3(

ones

eye

46

Page 47: MATLAB INTRODUCTION

Concatenation of Matrices

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

A = [ x y]

1 2 4 5

B = [x ; y]

1 2

4 5

47

Page 48: MATLAB INTRODUCTION

Matrices Operations

Given A and B:

Addition Subtraction Product Transpose

48

Page 49: MATLAB INTRODUCTION

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

49

Page 50: MATLAB INTRODUCTION

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

50

Page 51: MATLAB INTRODUCTION

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

51

Page 52: MATLAB INTRODUCTION

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

52

Page 53: MATLAB INTRODUCTION

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

53

Page 54: MATLAB INTRODUCTION

ACCESSING MATRIX ELEMENTS

An Element is a single number within a matrix or vector

To access elements of a matrix type the matrices’ name followed by round brackets containing a reference to the row and column number:

>> Variable_Name(Row_Number, Column_Number)

NOTE: In Excel you reference a value by Column, Row. In MATLAB you reference a value by Row, Column

54

Page 55: MATLAB INTRODUCTION

ACCESSING MATRIX ELEMENTS

To access Subject 3’s result for Test 3 In Excel (Column, Row):

D3

In MATLAB (Row, Column):

>> results(3, 4)

Excel MATLAB

2n

d

1st

1st 2nd

55

Page 56: MATLAB INTRODUCTION

CHANGING MATRIX ELEMENTS

The referenced element can also be changed

>> results(3, 4) = 10

or

>> results(3,4) = results(3,4) * 100

56

Page 57: MATLAB INTRODUCTION

ACCESSING MATRIX ROWS

You can also access multiple values from a Matrix using the : symbol

To access all columns of a row enter:

>> Variable_Name(RowNumber, :)

57

Page 58: MATLAB INTRODUCTION

ACCESSING MATRIX COLUMNS

To access all rows of a column

>> Variable_Name(:, ColumnNumber)

58

Page 59: MATLAB INTRODUCTION

CHANGING MATRIX ROWS OR COLUMNS

These reference methods can be used to change the values of multiple matrix elements

To change all of the values in a row or column to zero use

>> results(:, 3) = 0 >> results(:, 5) = results(:, 3) + results(:, 4)

59

Page 60: MATLAB INTRODUCTION

CHANGING MATRIX ROWS OR COLUMNS

To overwrite a row or column with new values >> results(3, :) = [10, 1, 1, 1] >> results(:, 3) = [1; 1; 1; 1; 1; 1; 1]

NOTE: Unless you are overwriting with a single value the data entered must be of the same size as the matrix part to be overwritten.

60

Page 61: MATLAB INTRODUCTION

ACCESSING MULTIPLE ROWS, COLUMNS

To access consecutive Rows or Columns use : with start and end points:

Multiple Rows: >> Variable_Name(start:end, :)

Multiple Columns: >> Variable_Name(:, start:end)

61

Page 62: MATLAB INTRODUCTION

ACCESSING MULTIPLE ROWS, COLUMNS

To access multiple non consecutive Rows or Columns use a vector of indexes (using square brackets []) Multiple Rows:

>>Variable_Name([index1, index2, etc.], :)

Multiple Columns: >>Variable_Name(:, [index1, index2, etc.])

62

Page 63: MATLAB INTRODUCTION

CHANGING MULTIPLE ROWS, COLUMNS

The same referencing can be used to change multiple Rows or Columns

>> results(3:6, :) = 0 >> results([3,6], :) = 0

63

Page 64: MATLAB INTRODUCTION

Control Statement

if

for

while

break

….

64

Page 65: MATLAB INTRODUCTION

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

65

Page 66: MATLAB INTRODUCTION

66

if statements

Can include multiple statements

Statements can also include other if statements (can nest if statements inside if statements)

Be careful not to overlap (crossover) if statements!

if A>10

% computations;

end

if condition

statements

true

false

if A>10

% computations;

else

% computations;

end

if condition

statements (1)

true false

statements (2)

Page 67: MATLAB INTRODUCTION

67

if-elseif statement

Can have several elseif conditions…

Else is optional and executes if all other tests fail

if A>10 % computations;

elseif A<10 % computations;

else % computations

end

if condition

statements (1)

true

false elseif condition

elseif condition

statements (2) statements (n)

false

… true

statements (n+1)

false else

Page 68: MATLAB INTRODUCTION

68

Switch-Case Statement

switch expression

case condition_1

%Do Stuff #1

case {condition_2a, condition_2b,…}

%Do Stuff #2

otherwise

%Do Other Stuff

end

Page 69: MATLAB INTRODUCTION

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

69

Page 70: MATLAB INTRODUCTION

70

for loop

Repeats for specified number of times

ALWAYS executes computation loop at least once!!!

Can use + or – increments

Can escape (BREAK) out of computational loop

for j=1:10

computations

done

for j=1:10

% computations; end

Page 71: MATLAB INTRODUCTION

Control Structures

While Loop Syntax

while (condition)

Matlab Commands

end

Dummy Example

while ((a>3) & (b==5))

Some Matlab Commands;

end

71

Page 72: MATLAB INTRODUCTION

72

while loop

Will do computational loop ONLY if while condition is met

Be careful to initialize while variable

Can loop forever if while variable is not updated within loop!!!

while

k<10

computations

done

change k

initialize k

k=0;

while k<10

% computations;

k=k+1;

end

Page 73: MATLAB INTRODUCTION

What are we interested in?

Matlab is too broad for our purposes in this course.

Matlab

Command Line

m-files

functions

mat-files

Command execution like DOS command

window

Series of Matlab

commands

Input Output

capability

Data storage/ loading

73

Page 74: MATLAB INTRODUCTION

M-Files

Script file: a collection of MATLAB commands

Function file: a definition file for one function

74

Page 75: MATLAB INTRODUCTION

Script Files

Any valid sequence of MATLAB commands can be in the script files.

Variables defined/used in script files are global, i.e., they present in the workspace.

75

Page 76: MATLAB INTRODUCTION

76

Page 77: MATLAB INTRODUCTION

77

Page 78: MATLAB INTRODUCTION

78

Page 79: MATLAB INTRODUCTION

Using Script M-files

» what M-files in the current directory C:\WINDOWS\Desktop\Matlab-Tutorials abc abc1 » abc 1 3 5 . . .

File Name

79

Page 80: MATLAB INTRODUCTION

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)

80

Page 81: MATLAB INTRODUCTION

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

81

Page 82: MATLAB INTRODUCTION

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

82

Page 83: MATLAB INTRODUCTION

Built-in Functions

Trigonometric functions

sin, cos, tan, sin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, sec, cot, …

Exponential functions

exp, log, log10, sqrt

Complex functions

abs, angle, imag, real, conj

Rounding and Remainder functions

floor, ceil, round, mod, rem, sign

83

Page 84: MATLAB INTRODUCTION

Built-in Functions

• sum – Sums the content of the variable passed

• prod – Multiplies the content of the variable passed

• mean – Calculates the mean of the variable passed

• median – Calculates the median of the variable passed

• mode – Calculates the Mode of the variable passed

• std – Calculates the standard deviation of the variable passed

• sqrt – Calculates the square root of the variable passed

• max – Finds the maximum of the data

• min – Finds the minimum of the data

• size – Gives the size of the variable passed

84

Page 85: MATLAB INTRODUCTION

MATLAB Logical Functions

MATLAB also supports some logical functions.

xor (exclusive or) True is returned as 1, false as 0.

any (x) returns 1 if any element of x is nonzero

all (x) returns 1 if all elements of x are nonzero

isnan (x) returns 1 at each NaN in x

isinf (x) returns 1 at each infinity in x

finite (x) returns 1 at each finite value in x

85

Page 86: MATLAB INTRODUCTION

Mathematical Functions

» x=sqrt(2)/2 x = 0.7071 » y=sin(x) y = 0.6496 »

86

Page 87: MATLAB INTRODUCTION

FUNCTIONS

Passing a vector to a function like sum, mean, std will calculate the property within the vector

>> sum([1,2,3,4,5])

= 15

>> mean([1,2,3,4,5])

= 3

87

Page 88: MATLAB INTRODUCTION

FUNCTIONS

When passing matrices the property, by default, will be calculated over the columns

88

Page 89: MATLAB INTRODUCTION

FUNCTIONS

More usefully you can now take the mean

and standard deviation of the data,

and add them to the array

89

Page 90: MATLAB INTRODUCTION

FUNCTIONS

You can find the maximum and minimum of some data using the max and min functions >> max(results)

>> min(results)

90

Page 91: MATLAB INTRODUCTION

Standard Deviation and Variance

Standard deviation is calculated using the std() function

std(X) : Calcuate the standard deviation of vector x

If x is a matrix, std() will return the standard deviation of each column

Variance (defined as the square of the standard deviation) is calculated

using the var() function

var(X) : Calcuate the variance of vector x

X = [1 5 9;7 15 22]

s = std(X)

s = 4.2426 7.0711 9.1924

Page 92: MATLAB INTRODUCTION

Reading Data from files

MATLAB supports reading an entire file and creating a matrix of the data with one statement.

>> load mydata.dat; % loads file into matrix.

% The matrix may be a scalar, a vector, or a

% matrix with multiple rows and columns. The

% matrix will be named mydata.

>> size (mydata) % size will return the number

% of rows and number of

% columns in the matrix

>> length (myvector) % length will return the total

% no. of elements in myvector

92

Page 93: MATLAB INTRODUCTION

MATLAB Demo

Demonstrations are invaluable since they give an indication of the MATLAB capabilities.

A comprehensive set are available by typing the command >>demo in MATLAB prompt.

93

Page 94: MATLAB INTRODUCTION

MATLAB Graphics

One of the best things about MATLAB is interactive

graphics

“plot” is the one you will be using most often

Many other 3D plotting functions -- plot3, mesh, surfc, etc.

Use “help plot” for plotting options

To get a new figure, use “figure” logarithmic plots available using semilogx, semilogy and

loglog

94

Page 95: MATLAB INTRODUCTION

plot(x,y) defaults to a blue line

plot(x,y,’ro’) uses red circles

plot(x,y,’g*’) uses green asterisks

If you want to put two plots on the same graph,

use “hold on”

plot(a,b,’r:’) (red dotted line)

hold on

plot(a,c,’ko’) (black circles)

Plotting Commands

95

Page 96: MATLAB INTRODUCTION

Color, Symbols, and Line Types

Use “help plot” to find available Specifiers

b blue . point - solid

g green o circle : dotted

r red x x-mark -. dashdot

c cyan + plus -- dashed

m magenta * star

y yellow s square

k black d diamond

v triangle (down)

^ triangle (up)

< triangle (left)

> triangle (right)

p pentagram

h hexagram

Colors Symbols Line Types

96

Page 97: MATLAB INTRODUCTION

PLOTTING

A basic plot >> x = [0:0.1:2*pi]

>> y = sin(x)

>> plot(x, y, ‘r.-’)

97

0 1 2 3 4 5 6 7-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

Page 98: MATLAB INTRODUCTION

PLOTTING

Plotting a matrix

MATLAB will treat each column as a different set of data

98

1 2 3 4 5 6 7 8 9 100.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

Page 99: MATLAB INTRODUCTION

PLOTTING

Some other functions that are helpful to create plots:

hold on and hold off

title

legend

axis

xlabel

ylabel

99

Page 100: MATLAB INTRODUCTION

PLOTTING

>> x = [0:0.1:2*pi]; >> y = sin(x); >> plot(x, y, 'b*-') >> hold on >> plot(x, y*2, ‘r.-') >> title('Sin Plots');

>> legend('sin(x)', '2*sin(x)');

>> axis([0 6.2 -2 2]) >> xlabel(‘x’); >> ylabel(‘y’); >> hold off 100

0 1 2 3 4 5 6-2

-1.5

-1

-0.5

0

0.5

1

1.5

2Sin Plots

x

y

sin(x)

2*sin(x)

Page 101: MATLAB INTRODUCTION

PLOTTING

Plotting data

>> results = rand(10, 3)

>> plot(results, 'b*')

>> hold on

>> plot(mean(results, 2), ‘r.-’)

101

1 2 3 4 5 6 7 8 9 100.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

Page 102: MATLAB INTRODUCTION

Plot Properties

XLABEL X-axis label.

XLABEL('text') adds text beside the X-axis on the current axis.

YLABEL Y-axis label.

YLABEL('text') adds text beside the Y-axis on the current axis.

...

xlabel('x

values');

ylabel('y

values');

Example

Page 103: MATLAB INTRODUCTION

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

Page 104: MATLAB INTRODUCTION

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

Page 105: MATLAB INTRODUCTION

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 1st Figure plot(x, y1,'bo-.'); xlabel('x values'); ylabel('y values'); % Plot y2 in the 2nd Figure figure y2 = x + 2; plot(x, y2, 'g+:');

Example

105

Page 106: MATLAB INTRODUCTION

Surface Plot

x = 0:0.1:2;

y = 0:0.1:2;

[xx, yy] = meshgrid(x,y);

zz=sin(xx.^2+yy.^2);

surf(xx,yy,zz)

xlabel('X axes')

ylabel('Y axes')

106

Page 107: MATLAB INTRODUCTION

contourf-colorbar-plot3-waterfall-contour3-mesh-surf

3 D Surface Plot

107

Page 108: MATLAB INTRODUCTION

Histograms

• Histograms are useful for showing the pattern of the whole data set

• Allows the shape of the distribution to be easily visualized

108

Page 109: MATLAB INTRODUCTION

Histograms

Matlab hist(y,m) command will generate a frequency histogram of vector y distributed among m bins

Also can use hist(y,x) where x is a vector defining the bin centers

Example: >>b=sin(2*pi*t)

>>hist(b,10); >>hist(b,[-1 -0.75 0 0.25 0.5 0.75 1]);

-1.5 -1 -0.5 0 0.5 1 1.50

5

10

15

20

25

30

35

40

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

5

10

15

20

25

30

35

40

45

109

Page 110: MATLAB INTRODUCTION

Histograms

The histc function is a bit more powerful and allows bin edges to be defined

[n, bin] = histc(x, binrange) x = statistical distribution binrange = the range of bins to plot eg: [1:1:10] n = the number of elements in each bin from vector x bin = the bin number each element of x belongs Use the bar function to plot the histogram

110

Page 111: MATLAB INTRODUCTION

Histograms

Example: >> test = round(rand(100,1)*10)

>> histc(test,[1:1:10])

>> Bar(test)

1 2 3 4 5 6 7 8 9 100

2

4

6

8

10

12

14

111

Page 112: MATLAB INTRODUCTION

Image Processing Toolbox

The Image Processing Toolbox is a collection of functions that extend the capability of the MATLAB ® numeric computing environment. The toolbox supports a wide range of image processing operations, including:

Geometric operations

Neighborhood and block operations

Linear filtering and filter design

Transforms

Image analysis and enhancement

Binary image operations

Region of interest operations

112

Page 113: MATLAB INTRODUCTION

Images in MATLAB

• MATLAB can import/export

several image formats:

– BMP (Microsoft Windows

Bitmap)

– GIF (Graphics Interchange

Files)

– HDF (Hierarchical Data Format)

– JPEG (Joint Photographic

Experts Group)

– PCX (Paintbrush)

– PNG (Portable Network

Graphics)

– TIFF (Tagged Image File Format)

– XWD (X Window Dump)

– raw-data and other types of image data

• Data types in MATLAB

– Double (64-bit double-precision

floating point)

– Single (32-bit single-precision

floating point)

– Int32 (32-bit signed integer)

– Int16 (16-bit signed integer)

– Int8 (8-bit signed integer)

– Uint32 (32-bit unsigned integer)

– Uint16 (16-bit unsigned integer)

– Uint8 (8-bit unsigned integer)

113

Page 114: MATLAB INTRODUCTION

MATLAB Image Types

Indexed images : m-by-3 color map

Intensity images : [0,1] or uint8

Binary images : {0,1}

RGB images : m-by-n-by-3

114

Page 115: MATLAB INTRODUCTION

Image Display

image - create and display image object

imagesc - scale and display as image

imshow - display image

colorbar - display colorbar

getimage- get image data from axes

truesize - adjust display size of image

zoom - zoom in and zoom out of 2D plot

115

Page 116: MATLAB INTRODUCTION

Image Conversion

Gray2ind - intensity image to index image

im2bw - image to binary

Im2double - image to double precision

Im2uint8 - image to 8-bit unsigned integers

Im2uint16 - image to 16-bit unsigned integers

Ind2gray - indexed image to intensity image

mat2gray - matrix to intensity image

rgb2gray - RGB image to grayscale

rgb2ind - RGB image to indexed image

116

Page 117: MATLAB INTRODUCTION

Indexed Images

» [x,map] = imread('trees.tif');

» imshow(x,map);

117

Page 118: MATLAB INTRODUCTION

Intensity Images

» image = ind2gray(x,map);

» imshow(image);

118

Page 119: MATLAB INTRODUCTION

Binary Images

» imshow(edge(image));

119

Page 120: MATLAB INTRODUCTION

RGB Images

120

Page 121: MATLAB INTRODUCTION

IMAGE ENHANCEMENT

Adjust intensity imadjust

histeq

Noise removal linear filtering

median filtering

adaptive filtering

>>im2 = histeq(im);

>>imshow(im2)

121

Page 122: MATLAB INTRODUCTION

Thanks

Questions ??

122