Anda di halaman 1dari 8

# Contents

What is Matlab?
Matrices

MATLAB Tutorial

Numerical Arrays
String Arrays

Elementary Math

Based on IPLab@SUT
Matlab Tutorial
1

Logical Operators
Math Functions

## Importing and Exporting Data

Contents

What is MATLAB?

Continued

Graphics Fundamentals

high-performance software

2D plotting
Subplots
3D plotting

Computation
Visualization
Easy-to-use environment.

## Editing and Debugging M-files

high-level language

## Script and Function Files

Basic Parts of an M-file
Flow Control Statements
M-file Programming
Data Types

Data types
Functions
Control flow statements
Input/output
Graphics
Object-oriented programming capabilities

## Calculations at the Command

Line

MATLAB as a calculator

-5/(4.8+5.32)^2
-5/(4.8+5.32)^2
ans
ans ==
-0.0488
-0.0488
(3+4i)*(3-4i)
(3+4i)*(3-4i)
ans
ans ==
25
25
cos(pi/2)
cos(pi/2)
ans
ans ==
6.1230e-017
6.1230e-017
exp(acos(0.3))
exp(acos(0.3))
ans
ans ==
3.5470
3.5470

General Functions
Assigning Variables
aa == 2;
2;
bb == 5;
5;
a^b
a^b

Semicolon
suppresses
screen output

ans
ans ==
32
32

Results
assigned to
ans if name
not specified

xx == 5/2*pi;
5/2*pi;
yy == sin(x)
sin(x)
yy ==
11
zz == asin(y)
asin(y)
zz ==

## whos: List current variables

clear: Clear variables and functions
from memory
cd: Change current working
directory
ls: List files in directory

() parentheses for
function inputs

1.5708
1.5708

## A Note about Workspace:

Numbers stored in double-precision floating point format

10

Getting help

Matrices

help command
lookfor command
Printable Documents

(>>help)
(>>lookfor)

Matlabroot\help\pdf_doc\

11

12

## Entering Numeric Arrays

a=[1
a=[1 2;3
2;3 4]
4]
aa ==
11
33

Row separator
semicolon (;)

Use square
brackets [ ]

22
44

A=

b=[-2.8,
b=[-2.8, sqrt(-7),
sqrt(-7), (3+5+6)*3/4]
(3+5+6)*3/4]
bb ==
-2.8000
-2.8000

00 ++ 2.6458i
2.6458i

## Column separator b(2,5) = 23

b(2,5) = 23
space / comma (,)

## Any MATLAB expression can be entered as a matrix

element
Matrices must be rectangular. (Set undefined elements to zero)

Creating sequences:
colon operator (:)

## Utility functions for

creating matrices.

15

0.6068
0.6068
0.4860
0.4860

11

16

21

1.2

12

17

25

22

7.2 3

13

18

11 23

0.5

14

19

56

24

23

83

10

13

15

20

10

25

Use [ ] to combine
existing arrays as
matrix elements

11
22
33
44
yy == 2:-0.5:0
2:-0.5:0
yy ==
2.0000
2.0000 1.5000
1.5000 1.0000
1.0000
zz == rand(2,4)
rand(2,4)
zz ==
0.9501
0.9501
0.2311
0.2311

0.8913
0.8913
0.7621
0.7621

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

Numerical Array
Concatenation

w=[1
w=[1 2;3
2;3 4]
4] ++ 55
ww ==
66
77
88
99
xx == 1:5
1:5
xx ==

10

14

## Entering Numeric Arrays

Scalar expansion

Columns
(n)
3
4

Rows (m) 3
00
00
00 23.0000
23.0000

1
2

10.5000
10.5000

bb ==
-2.8000
-2.8000 00 ++ 2.6458i
2.6458i 10.5000
10.5000
00
00
00

13

## Entering and Generating Matrices

Subscripts
Scalar Expansion
Concatenation
Deleting Rows and Columns
Array Extraction
Matrix and Array Multiplication

11
33

22
44

Use square
brackets [ ]

cat_a=[a,
cat_a=[a, 2*a;
2*a; 3*a,
3*a, 4*a;
4*a; 5*a,
5*a, 6*a]
6*a]
cat_a
cat_a ==
11
22
22
44
33
44
66
88
Column separator:
33
66
44
88
4*a
99
12
12
16
space / comma (,)
12
12
16
55
10
6
12
10
6
12
15
20
18
24
15
20
18
24

Row separator:
semicolon (;)

55

0.5000
0.5000

a=[1
a=[1 2;3
2;3 4]
4]
aa ==

00

0.4565
0.4565
0.0185
0.0185

16

Note:
The resulting matrix must be rectangular

## Deleting Rows and Columns

A=[1
A=[1 55 9;4
9;4 33 2.5;
2.5; 0.1
0.1 10
10 3i+1]
3i+1]
AA ==
1.0000
1.0000
4.0000
4.0000

5.0000
5.0000
3.0000
3.0000

0.1000
0.1000
A(:,2)=[]
A(:,2)=[]
AA ==

10.0000
10.0000

1.0000
1.0000
4.0000
4.0000

9.0000
9.0000
2.5000
2.5000

9.0000
9.0000
2.5000
2.5000

A=

1.0000+3.0000i
1.0000+3.0000i

A(3,1)
A(3)

0.1000
1.0000
0.1000
1.0000 ++ 3.0000i
3.0000i
A(2,2)=[]
A(2,2)=[]
???
Indexed
empty
matrix
assignment
??? Indexed empty matrix assignment is
is not
not allowed.
allowed.

17

10

1.2 7

7.2

0.5 9

23

11

16

9 12

17

25 22

13

18

11 23

4 14

19

56 24

83 10 1315

20

10 25

21

A(1:5,5) A(1:end,end)
A(:,5)
A(:,end)
A(21:25) A(21:end)

A(4:5,2:3)
A([9 14;10 15])

18

## Matrix Manipulation Functions

Matrix Multiplication
aa == [1
[1 22 33 4;
4; 55 66 77 8];
8];
bb == ones(4,3);
ones(4,3);
cc == a*b
a*b

[2x4]*[4x3]

## zeros: Create an array of all zeros

ones: Create an array of all ones
eye: Identity Matrix
rand: Uniformly distributed random numbers
diag: Diagonal matrices and diagonal of a matrix
size: Return array dimensions
repmat: Replicate and tile a matrix

[2x4]
[4x3]
[2x3]

cc ==
10
10
26
26

10
10
26
26

10
10
26
26

## a(2nd row).b(3rd column)

Array Multiplication
aa == [1
[1 22 33 4;
4; 55 66 77 8];
8];
bb == [1:4;
[1:4; 1:4];
1:4];
cc == a.*b
a.*b
cc ==
11
55

44
12
12

99
21
21

16
16
32
32

c(2,4) = a(2,4)*b(2,4)

19

20

Elementary Math

## det: Matrix determinant

inv: Matrix inverse
eig: Evaluate eigenvalues and eigenvectors
rank: Rank of matrix

Logical Operators
Math Functions
Polynomial and
Interpolation

21

25

## Elementary Math Function

Logical Operations
= = equal to
>

greater than

<

less than

<= less or equal
~

not

&

and

or

## abs, sign: Absolute value and Signum

Function
sin, cos, asin, acos: Triangular functions
exp, log, log10: Exponential, Natural and
Common (base 10) logarithm
ceil, floor: Round toward infinities
fix: Round toward zero

Mass
Mass == [-2
[-2 10
10 NaN
NaN 30
30 -11
-11 Inf
Inf 31];
31];
each_pos
each_pos == Mass>=0
Mass>=0

each_pos
each_pos ==
00
11
00
11
00
11
11
all_pos
all_pos == all(Mass>=0)
all(Mass>=0)
all_pos
all_pos ==
00
all_pos
all_pos == any(Mass>=0)
any(Mass>=0)
all_pos
all_pos ==
11
pos_fin
pos_fin == (Mass>=0)&(isfinite(Mass))
(Mass>=0)&(isfinite(Mass))
pos_fin
pos_fin ==
00
11
00
11
00
00
11

isfinite(), etc. . . .
all(), any()
find

26

Note:
1 = TRUE
0 = FALSE

27

## round: Round to the nearest integer

sqrt: Square root function
real, imag: Real and Image part of
complex
rem: Remainder after division

## max, min: Maximum and Minimum of arrays

mean, median: Average and Median of arrays
std, var: Standard deviation and variance
sort: Sort elements in ascending order
sum, prod: Summation & Product of Elements

28

## Read formatted data, reusing the

format string N times.

save
save fname
fname
save
save fname
fname xx yy zz
save
save fname
fname -ascii
-ascii
save
fname
save fname -mat
-mat

32

## Import and Exporting Numeric Data

with General ASCII delimited files

fname
fname xx yy zz
fname -ascii
-ascii
fname
-mat

33

Graphics

Graphics
Fundamentals

Basic Plotting
plot, title, xlabel, grid,
legend, hold, axis

Editing Plots

Property Editor

## Mesh and Surface Plots

meshgrid, mesh, surf,
colorbar, patch, hidden

Handle Graphics
35

36

Sample Plot

2-D Plotting
Syntax:

Title

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

Example:
x=[0:0.1:2*pi];
x=[0:0.1:2*pi];
y=sin(x);
y=sin(x);
z=cos(x);
z=cos(x);
plot(x,y,x,z,'linewidth',2)
plot(x,y,x,z,'linewidth',2)
title('Sample
title('Sample Plot','fontsize',14);
Plot','fontsize',14);
xlabel('X
xlabel('X values','fontsize',14);
values','fontsize',14);
ylabel('Y
values','fontsize',14);
ylabel('Y values','fontsize',14);
legend('Y
legend('Y data','Z
data','Z data')
data')
grid
grid on
on

37

Ylabel

Legend
38

Subplots
Syntax:

Grid

Xlabel

## Surface Plot Example

xx == 0:0.1:2;
0:0.1:2;
yy == 0:0.1:2;
0:0.1:2;
[xx,
[xx, yy]
yy] == meshgrid(x,y);
meshgrid(x,y);
zz=sin(xx.^2+yy.^2);
zz=sin(xx.^2+yy.^2);
surf(xx,yy,zz)
surf(xx,yy,zz)
xlabel('X
xlabel('X axes')
axes')
ylabel('Y
ylabel('Y axes')
axes')

subplot(rows,cols,index)
subplot(rows,cols,index)
subplot(2,2,1);
subplot(2,2,1);

subplot(2,2,2)
subplot(2,2,2)
...
...
subplot(2,2,3)
subplot(2,2,3)
...
...
subplot(2,2,4)
subplot(2,2,4)
...
...

39

40

## Specialized Plotting Routines

bar-bar3h-hist-area-pie3-rose

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

41

42

## Editing and Debugging M-Files

Debugging

What is an M-File?
The Editor/Debugger
Search Path
Debugging M-Files

Select
Workspace
Set AutoBreakpoints

## Types of Errors (Syntax Error and Runtime

Error)
Using keyboard and ; statement
Setting Breakpoints
Stepping Through

tips

Step Out

Examining Values

## Selecting the Workspace

Viewing Datatips in the Editor/Debugger
Evaluating a Selection

43

44

Script Files

Programming and
Dubugging

## Work as though you typed commands into

MATLAB prompt
Variable are stored in MATLAB workspace

Function Files

45

46

## Let you make your own MATLAB Functions

All variables within a function are local
All information must be passed to functions as
parameters
Subfunctions are supported

Output Arguments

Function Name

if Statement

Input Arguments

if
if ((attendance
((attendance >=
>= 0.90)
>= 60))
60))
pass
pass == 1;
1;

end;
end;

## function y = mean (x)

% MEAN Average or mean value.
% For vectors, MEAN(x) returns the mean value.

while Loops

## % For matrices, MEAN(x) is a row vector

% containing the mean value of each column.

eps
eps == 1;
1;
while
while (1+eps)
(1+eps) >> 11

[m,n] = size(x);

Function Code

if m == 1

eps
eps == eps/2;
eps/2;
end
end
eps
=
eps*2
eps = eps*2

m = n;
end
y = sum(x)/m;

47

48

for Loop

## M-file Programming Features

SubFunctions
Varying number of input/output
arguments
Local and Global Variables
Obtaining User Input

aa == zeros(k,k)
zeros(k,k) %% Preallocate
Preallocate matrix
matrix
for
for mm == 1:k
1:k
for
for nn == 1:k
1:k
a(m,n)
a(m,n) == 1/(m+n
1/(m+n -1);
-1);

end
end

end
end

switch Statement

## Prompting for Keyboard Input

Pausing During Execution

method
method == 'Bilinear';
'Bilinear';
switch
switch lower(method)
lower(method)

## Errors and Warnings

case
case {'linear','bilinear'}
{'linear','bilinear'}
disp('Method
disp('Method is
is linear')
linear')

case
case 'cubic'
'cubic'
disp('Method
disp('Method is
is cubic')
cubic')

## Shell Escape Functions (! Operator)

Optimizing MATLAB Code

otherwise
otherwise
disp('Unknown
disp('Unknown method.')
method.')

49

end
end
Method
Method is
is linear
linear

50

Function M-file
function
function rr == ourrank(X,tol)
ourrank(X,tol)
%% rank
rank of
of aa matrix
matrix
ss == svd(X);
svd(X);
if
if (nargin
(nargin ==
== 1)
1)
tol
tol == max(size(X))
max(size(X)) ** s(1)*
s(1)* eps;
eps;
end
end
rr == sum(s
>
tol);
sum(s > tol);

Data Types
Multiple Input Arguments
use ( )
r=ourrank(rand(5),.1);

function
function [mean,stdev]
[mean,stdev] == ourstat(x)
ourstat(x)
[m,n]
[m,n] == size(x);
size(x);
if
m
==
1
if m == 1
m = n;
[m std]=ourstat(1:9); endm = n;
end
mean
mean == sum(x)/m;
sum(x)/m;
stdev
stdev == sqrt(sum(x.^2)/m
sqrt(sum(x.^2)/m mean.^2);
mean.^2);

Numeric Arrays
Multidimensional Arrays
Structures and Cell Arrays

Multiple Output
Arguments, use [ ]

51

Vectorizing loops
Preallocating Arrays

52

Multidimensional Arrays

Structures

1, the row.

## Arrays with named data containers called fields.

patient.name='John
patient.name='John Doe';
Doe';
patient.billing
patient.billing == 127.00;
127.00;
patient.test=
[79
75
patient.test= [79 75 73;
73;

AA == pascal(4);
pascal(4);
The second references dimension 2, A(:,:,2) = magic(4)
A(:,:,2) = magic(4)
the column.

The page.

0
16

5
1
9
2
4
3

1
1

53

20 30 130
110 100 80
1
1
70 60 120
3
4
14 15
1
6 10

10

Page N

0
0

20

A(:,:,1)
A(:,:,1) ==
11
11
11
11
22
33
11
33
66
11
44
10
10
A(:,:,2)
A(:,:,2) ==
16
22
33
16
55
11
10
11
10
99
77
66
44
14
15
14
15
A(:,:,9)
A(:,:,9) ==
diag(ones(1,4));
diag(ones(1,4));

180
180 178
178 177.5;
177.5;
220
220 210
210 205];
205];

11
44
10
10
20
20

## Also, Build structure arrays using the struct function.

Array of structures
patient(2).name='Katty
patient(2).name='Katty Thomson';
Thomson';
Patient(2).billing
Patient(2).billing == 100.00;
100.00;
Patient(2).test=
[69
25
Patient(2).test= [69 25 33;
33; 120
120 128
128 177.5;
177.5; 220
220

13
13
88
12
12
11

Page 1

Cell Arrays
Array for which the elements are cells and can hold
other MATLAB arrays of different types.
A(1,1)
A(1,1) == {[1
{[1 44 3;
3;

00 55 8;
8;
77 22 9]};
9]};
A(1,2)
A(1,2) == {'Anne
{'Anne Smith'};
Smith'};
A(2,1)
A(2,1) == {3+7i};
{3+7i};
A(2,2)
A(2,2) == {-pi:pi/10:pi};
{-pi:pi/10:pi};

54

210
210 205];
205];

## Next Tutorial Session

Image Processing Toolbox
Movie Making
Problem Set 1

## Using braces {} to point to elements of cell array

Using celldisp function to display cell array
55

Questions?

## Getting more help

Contact http://www.mathworks.com/support
You can find more help and FAQ about