You are on page 1of 26

MH2401 Algorithms & Computing III Slides 4

Chua Chek Beng Henk Hollmann Punarbasu Purkayastha

August 19, 2013

Recap
Index of vectors and matrices starts from 1 Vectors and matrices can be indexed by using arrays or by

using logical indexing Matrix elements can be accessed using two ways
- Use pairs of arrays M (r, c) - Use linear indexing M (v ) Conjugate transpose ( ) and transpose ( . ) operations can be

performed on vectors and matrices Arithmetic operations on matrices: +, , , /, Solve linear equations using \ Elementwise arithmetic operations: ., ., ./, .\, . Special matrices: zeros, ones, diag, eye Matrices (of appropriate dimensions) can be concatenated using just semicolon ; , space and comma , . One can also use the commands cat , horzcat , vertcat Recursive functions

Topics for today

Recursive functions Vectorization How to plot vectors and functions How to change the parameters of the plots Noninteractive plotting Plot mathematical functions

Functions - recursion
A recursive function is one which calls itself from within its

own body
1 2 3 4 5 6 7 8

function o u t = f a c t ( n ) if n == 1 % base case to stop recursion o u t = 1 ; return ; elseif n == 0 % extra case o u t = 1 ; return ; end o u t = n f a c t ( n 1) ; % calls itself end

Note: the return statement here makes the function exit immediately, skipping all the lines following the return

keyword

Functions - recursion
1 2 3 4 5 6 7 8

% Another way of writing fact , without ' return ' function o u t = f a c t ( n ) if n == 1 | | n == 0 out = 1 ; else o u t = n f a c t ( n 1) ; end end

out = 6 fact(3) : 3 fact(2) fact(2) : 2 fact(1) fact(1) 32 out = 2 21 out = 1 base case

Functions - recursion
For nonnegative integers n, k n k = n n1 n! = k !(n k )! k k1

Base case? Look at the domain where the function is

mathematically dened.
1 For what values of k, n is n k mathematically dened?

Ans: For 0 k n, integer k, n.


Fact: for k = 0, n k = 1, for any n 0.

Base case: k = 0.
Example:

5 3
1 n k

5 4 3 2

5 4 3 3 2 1

5 4 3 2 . 3 2 1 0

can be dened for real valued n, k but this case is not considered here.

Vectorization

Vectorization is the method by which one can avoid writing for and while loops. Instead, convert the for or while loops to equivalent vector or

matrix operations by using


- Inbuilt MATLAB functions such as find, sum, prod, cumsum, (search for vectorization and performance in the doc for other examples) - Elementwise mathematical operations such as ., ., ./, .\ Why is vectorization useful? - Faster execution of programs - Plots

Vectorization

1 2 3 4 5 6 7 8

% Sum of all primes below 10 ,000 - not vectorized % This script is saved in a file called example .m s = 0; for k = 1 : 1 0 0 0 0 if i s p r i m e ( k ) s = s + k; end end >> tic ; e x a m p l e ; t = toc ; >> disp ( [ sum = , num2str ( s ) , . . . , t i m e t a k e n = , num2str ( t ) ] ) ; sum = 5 7 3 6 3 9 6 , t i m e t a k e n = 0 . 6 1 0 5 9

Vectorization
1 2 3 4

% Sum of all primes below 10 ,000 - vectorized % This script is saved as examplevec .m v = 1:10000; s 2 = sum ( v ( i s p r i m e ( v ) ) ) ; >> tic ; e x a m p l e v e c ; t 2 = toc ; >> disp ( [ sum = , num2str ( s 2 ) , . . . , t i m e t a k e n = , num2str ( t 2 ) ] ) ; sum = 5 7 3 6 3 9 6 , t i m e t a k e n = 0 . 0 9 5 9

1 2 3

% Sum all 1/p for primes p below 10 ,000 v = 1:10000; s 3 = sum ( 1 . / v ( i s p r i m e ( v ) ) ) ; % Using elementwise ./

Plots
plot(Y) plots the one-dimensional array Y at the points (i, Y (i)) for i = 1, . . . , n where n is the length(Y) Consecutive points (i, Y (i)) and (i + 1, Y (i + 1)) are joined

by straight lines
>> plot ( [ 2 4 6 4 6 ] )
6

2 1

The plot opens in a separate interactive window One can change the parameters of the plot from this window For noninteractive (and faster) usage, we will consider how to

change the parameters of the plot by MATLAB commands

Plots
plot(X, Y) plots the points (X (i), Y (i)) Both vectors must have the same length Consecutive points (X (i), Y (i)) and (X (i + 1), Y (i + 1)) are

joined by straight lines


>> X = pi / 2 : pi / 2 0 : pi / 2 ; >> plot (X , sin (X) )
1

0.5

0.5

1 2

Interactively change plot parameters


Use the arrow button to start up interactive mode for changing plot parameters

Noninteractively change plot parameters


plot(X, Y) plots the points (X (i), Y (i)).

Plot only the points (see doc linespec for types of Marker)
>> X = pi / 2 : pi / 2 0 : pi / 2 ; >> plot (X , sin (X) , o )

0.5

0.5

1 2

Noninteractively change plot parameters


plot(X, Y) plots the points (X (i), Y (i)).

Plot both line and markers (see doc linespec for types of lines)
>> X = pi / 2 : pi / 2 0 : pi / 2 ; >> plot (X , sin (X) , o )

0.5

0.5

1 2

Noninteractively change plot parameters


plot(X, Y) plots the points (X (i), Y (i)).

Change LineStyle and Marker style (see doc linespec )


>> X = pi / 2 : pi / 2 0 : pi / 2 ; >> plot (X , sin (X) , .d )

0.5

0.5

1 2

Noninteractively change plot parameters


plot(X, Y) plots the points (X (i), Y (i)).

Change the Color to red (r) (see doc linespec for types of colors)
>> X = pi / 2 : pi / 2 0 : pi / 2 ; >> plot (X , sin (X) , o r )

0.5

0.5

1 2

Noninteractively change plot parameters


plot(X, Y) plots the points (X (i), Y (i)).

Add x, y labels and a title


>> >> >> >> X = pi / 2 : pi / 2 0 : pi / 2 ; plot (X , sin (X) , o r ) ; xlabel ( x a x i s ) ; ylabel ( s i n ( x ) ) title ( P l o t o f s i n ( x ) )

Plot of sin(x) 1 0.5 sin(x) 0 0.5 1 2

0 xaxis

Noninteractively change plot parameters


plot(X, Y) plots the points (X (i), Y (i)).

Add a grid
>> >> >> >> X = pi / 2 : pi / 2 0 : pi / 2 ; plot (X , sin (X) , o r ) ; xlabel ( x a x i s ) ; ylabel ( s i n ( x ) ) title ( P l o t o f s i n ( x ) ) ; grid on ;

Plot of sin(x) 1 0.5 sin(x) 0 0.5 1 2

0 xaxis

Noninteractively change plot parameters


plot(X, Y) plots the points (X (i), Y (i)).

Print to a le (see doc print)


>> >> >> >> >> >> X = pi / 2 : pi / 2 0 : pi / 2 ; plot (X , sin (X) , o r ) ; xlabel ( x a x i s ) ; ylabel ( s i n ( x ) ) title ( P l o t o f s i n ( x ) ) ; grid on ; print dpng m y p l o t . png % Lossless PNG format print d j p e g m y p l o t . j p g % Lossy JPEG format

Multiple plots in same axes


1. plot(X1, Y1, linespec1 , X2, Y2, linespec2 , ...)
>> X1 = pi / 2 : pi / 2 0 : pi / 2 ; X2 = 2 : 0 . 0 2 : 2 ; >> plot ( X1 , sin ( X1 ) , b , X2 , cos ( X2 ) , r )
1

0.5

0.5

1 2

2. hold on (plot styles are reset for every plot) (Use hold o to stop hold)
>> hold on >> plot ( X1 , sin ( X1 ) , >> plot ( X2 , cos ( X2 ) , b ) r )

Multiple plots in same axes


1. hold all automatically cycle through colors and linestyles. Use hold o to stop holding gure properties.
1 2 3 4 5 6

% plot of sin(x), sin (2x), ... , sin(nx) function p l o t s i n ( n ) hold all ; x = pi : 0 . 1 : pi ; for k = 1 : n , plot ( x , sin ( k x ) ) ; end hold o f f ; % Use this to stop ' hold ' end
1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1 4

Multiple plots and legends


legend( label1 , label2 ,...) creates a legend for your plot. The order in which you enter the labels should be the same

order in which the plots are generated.


>> X1 = pi / 2 : pi / 2 0 : pi / 2 ; X2 = 2 : 0 . 0 2 : 2 ; >> plot ( X1 , sin ( X1 ) , b , X2 , cos ( X2 ) , r ) >> legend ( s i n ( x ) , c o s ( x ) , L o c a t i o n , B e s t )
1 0.5 0 0.5 sin(x) cos(x) 1 2 1 0 1 2

figure()

create empty plots

Empty plots or new plots can be initiated by using figure >> figure ( ) % create a new blank plot window After generating the gure, use close to close the window Very useful in scripts and functions. figure( visible , o ) to turn o window Example script: generate a gure and print it to a le
1 2 3 4 5 6 7 8 9 10

figure ( v i s i b l e , o f f ) X1 = pi / 2 : pi / 2 0 : pi / 2 ; X2 = 2 : 0 . 0 2 : 2 ; plot ( X1 , sin ( X1 ) , b , X2 , cos ( X2 ) , r ) xlabel ( x v a l u e s ) ; ylabel ( s i n ( x ) and c o s ( x ) ) ; title ( p l o t o f s i n ( x ) and c o s ( x ) ) legend ( s i n ( x ) , c o s ( x ) , L o c a t i o n , B e s t ) print dpng s i n c o s . png close % Don ' t forget to close the figure !

Plot using

ezplot

Use ezplot ( f , [xmin, xmax]) to plot mathematical expressions f that are provided as strings >> e z p l o t ( s i n ( x ) , [ 2 , 2 ] ) Setting properties of the plot requires usage of set >> >> >> >> >> h = e z p l o t ( s i n ( x ) , [ 2 , 2 ] ) ; % plot handle set ( h , L i n e S t y l e , , C o l o r , r ) set ( h , L i n e W i d t h , 2 ) xlabel ( x a x i s ) ; ylabel ( s i n ( x ) ) title ( P l o t o f s i n ( x ) )
Plot of sin(x)

1 0.5
sin(x)

0 0.5 1 2 1 0
xaxis

We saw two ways of plotting

Plot x2 + 2x from 0 to 4.5 1. Using plot


1 2 3

X = 0:0.1:4.5; F = X. 2 + 2 . X ; plot (X , F )

2. Using ezplot
1 2

f = x 2 + 2 x ; ezplot ( f , [0 , 4.5])

Exercise

1. Test out all the examples given in these slides. Ensure that you understand the main concepts.

You might also like