# Lecture 2 Programming in MATLAB CS 175 Project in by ywr18717

VIEWS: 60 PAGES: 50

• pg 1
```									                       Lecture 2: Programming in MATLAB

CS 175: Project in AI
Fall 2007

Department of Computer Science
University of California, Irvine

CS 175, Fall 2007: Professor Padhraic Smyth                                       Slide Set 2: MATLAB programming : 1
Assignment 1

• Assignment 1:
– MATLAB tutorials
– Euclidean distance between x and y (2 vectors)
• distance = square root [ sum (x_i - y_i)^2 ]
• sum is over the components of the vectors
– 1 page on face recognition in digital cameras
– submit your completed assignment by Thursday 9:30 am

• Any issues with finding machines with MATLAB?
– Note only some machines in 364 have MATLAB. See Web page.
– You can also ask the lab attendant in 364 for help.

• Questions on assignment at the end of the lecture

CS 175, Fall 2007: Professor Padhraic Smyth                          Slide Set 2: MATLAB Programming 2
Outline of Today’s Lecture

• Data Types
– arrays: char, numeric, struct, logical, cell, others

• Operators
– arithmetic, relational, logical

• Flow Control
– conditionals, case, while, etc.

• M-functions
– syntax
– examples of simple functions
– writing and debugging a simple MATLAB function

• Next lecture:
– Classification algorithms

CS 175, Fall 2007: Professor Padhraic Smyth                               Slide Set 2: MATLAB Programming 3
Data Types in MATLAB

Array

Logical
Char                                 Numeric           Structure                   Others
‘a’                                                    image.width = 120
image.name = ‘face1’

Uint8
Double
(8 bit, from 0 to 255,
e.g., 3.2567
e.g., pixel values)
(8 bytes)

CS 175, Fall 2007: Professor Padhraic Smyth                                      Slide Set 2: MATLAB Programming 4
Uint8 and Doubles

• Double
– almost all MATLAB functions
• expect doubles as arguments
• return doubles

CS 175, Fall 2007: Professor Padhraic Smyth            Slide Set 2: MATLAB Programming 5
Uint8 and Doubles

• Double
– almost all MATLAB functions
• expect doubles as arguments
• return doubles

CS 175, Fall 2007: Professor Padhraic Smyth     Slide Set 2: MATLAB Programming 6
Uint8 and Doubles

• Double
– almost all MATLAB functions        » a = 1:10
• expect doubles as arguments    a=
1 2 3 4 5 6 7 8 9 10
• return doubles                 » b = uint8(a)
• e.g.,                          b=
1 2 3 4 5 6 7 8 9 10
» whos
Name      Size Bytes Class

a       1x10       80 double array
b       1x10       10 uint8 array

» b*2
??? Error using ==> *
• need to convert uint8 to   Function '*' not defined for variables of class 'uint8'.
double before performing
any math operations        » (double(b))*2

ans =

2   4   6   8 10 12 14 16 18 20

CS 175, Fall 2007: Professor Padhraic Smyth                              Slide Set 2: MATLAB Programming 7
Char Data Type

» c = ['hello'];

» whos
Name             Size            Bytes   Class
c               1x5              10     char array

Grand total is 5 elements using 10 bytes

» c(1)
ans = h

CS 175, Fall 2007: Professor Padhraic Smyth                        Slide Set 2: MATLAB Programming 8
Char Data Type

» d = [c,' again'];
» c = ['hello'];                                       »d
d = hello again
» whos                                                 »
Name             Size            Bytes   Class        » b = ['hello';'again'];
c               1x5              10     char array   » size(b)
ans = 2 5
Grand total is 5 elements using 10 bytes            »b
b=
» c(1)                                                    hello
ans = h                                                   again
»

CS 175, Fall 2007: Professor Padhraic Smyth                                  Slide Set 2: MATLAB Programming 9
Char Data Type

» d = [c,' again'];
» c = ['hello'];                                       »d
d = hello again
» whos                                                 »
Name             Size            Bytes   Class        » b = ['hello';'again'];
c               1x5              10     char array   » size(b)
ans = 2 5
Grand total is 5 elements using 10 bytes            »b
b=
» c(1)                                                    hello
ans = h                                                   again
»

Many string functions available, e.g., strcat, num2str, etc

CS 175, Fall 2007: Professor Padhraic Smyth                                  Slide Set 2: MATLAB Programming 10
Struct Data Type

image.name = 'Tom';

Field Name
Structure
Name

CS 175, Fall 2007: Professor Padhraic Smyth                          Slide Set 2: MATLAB Programming 11
Struct Data Type

image.name = 'Tom';
» image.height = 3;

» image.width = 3;

» image.data = [8 10 2; 22 7 22; 2 4 7];

» whos
Name        Size     Bytes Class

image      1x1       590 struct array

Grand total is 18 elements using 590 bytes

CS 175, Fall 2007: Professor Padhraic Smyth                                   Slide Set 2: MATLAB Programming 12
Arrays of Structures

» image(1) = image;
» image(2).name = 'Mary'
» image(2).width = 4;
» image(2).height = 4;
» whos
Name       Size     Bytes Class

image        1x2          894 struct array

Grand total is 28 elements using 894 bytes

» image

image =

1x2 struct array with fields:
name
height
width
data

CS 175, Fall 2007: Professor Padhraic Smyth                 Slide Set 2: MATLAB Programming 13
Arrays of Structures

» image(1) = image;                           » image(2)
» image(2).name = 'Mary'
» image(2).width = 4;                         ans =
» image(2).height = 4;
» whos                                           name: 'Mary'
Name       Size     Bytes Class                height: 4
width: 4
image        1x2          894 struct array      data: []
Grand total is 28 elements using 894 bytes    » image(1)
» image                                       ans =
image =                                          name: 'Tom'
height: 3
1x2 struct array with fields:                   width: 3
name                                           data: [3x3 double]
height
width
data

CS 175, Fall 2007: Professor Padhraic Smyth                   Slide Set 2: MATLAB Programming 14
Operators

• Arithmetic
– numeric computations, e.g., 2^10

• Relational
– quantitative comparison of operands
– e.g., a < b

• Logical
– AND, OR, NOT, etc
– result of type Logical, 1 (TRUE) or 0 (FALSE)

CS 175, Fall 2007: Professor Padhraic Smyth                          Slide Set 2: MATLAB Programming 15
Arithmetic Operators

• Transpose, a’

• Power, a^2

– a(1)*b(2)
– a*b
• works if a and b are matrices
with appropriate dimensions
(columns(a) = rows(b))
– a.*b (element by element)

• except for matrix operations, most
operands must be of the same size,
unless one is a scalar

CS 175, Fall 2007: Professor Padhraic Smyth            Slide Set 2: MATLAB Programming 16
Arithmetic Operators

• Transpose, a’                              » a = [2 3];
» b = [4 5];
» a(1)*b(2)
• Power, a^2                                 ans =
10

• Addition, multiplication, division         » a*b
??? Error using ==> *
– a(1)*b(2)
Inner matrix dimensions must agree.
– a*b
• works if a and b are matrices   » a*b'
with appropriate dimensions     ans =
23
(columns(a) = rows(b))
– a.*b (element by element)           » a.*b
ans =

• except for matrix operations, most            8 15
operands must be of the same size,
unless one is a scalar                     » b/2
ans =
2.0000 2.5000

CS 175, Fall 2007: Professor Padhraic Smyth                           Slide Set 2: MATLAB Programming 17
Relational Operators

• <, <=, >, >=, ==, ~=

• compare corresponding elements
of arrays with same dimensions

• if one is scalar, one is not, the scalar
is compared with each element

• result is of type Logical
– element by element 1 or 0

CS 175, Fall 2007: Professor Padhraic Smyth             Slide Set 2: MATLAB Programming 18
Relational Operators

»a
• <, <=, >, >=, ==, ~=                         a= 2           3

• compare corresponding elements               »b
of arrays with same dimensions               b=4           5

• if one is scalar, one is not, the scalar     »a>b
is compared with each element                ans = 0            0

• result is of type Logical                    »b>a
– element by element 1 or 0            ans = 1            1

»a>2
ans = 0            1

CS 175, Fall 2007: Professor Padhraic Smyth             Slide Set 2: MATLAB Programming 19
Flow Control

• If, else, endif
if index<100
statements
else
statements
end

• For…..
For i = 1:100
statements
end

• Switch, while, case, etc

CS 175, Fall 2007: Professor Padhraic Smyth   Slide Set 2: MATLAB Programming 20
Vectorization of Computation

tic
for i=1:100000
y(i) = log(i);
end
toc

CS 175, Fall 2007: Professor Padhraic Smyth   Slide Set 2: MATLAB Programming 21
Vectorization of Computation

tic
for i=1:100000                         elapsed_time =
y(i) = log(i);
end                                     168.78 seconds
toc

CS 175, Fall 2007: Professor Padhraic Smyth               Slide Set 2: MATLAB Programming 22
Vectorization of Computation

tic
for i=1:100000                         elapsed_time =
y(i) = log(i);
end                                     168.78 seconds
toc

tic
i=1:100000;
z = log(i);
toc

CS 175, Fall 2007: Professor Padhraic Smyth               Slide Set 2: MATLAB Programming 23
Vectorization of Computation

tic
for i=1:100000                                                     elapsed_time =
y(i) = log(i);
end                                                                  168.78 seconds
toc

tic
i=1:100000;                                                        elapsed_time =
z = log(i);
toc                                                                   0.053 seconds

First method calls the log function 100,000 times,
Second method only calls it once (much faster)

CS 175, Fall 2007: Professor Padhraic Smyth                                           Slide Set 2: MATLAB Programming 24
Memory Preallocation

• What happens in the previous example if we preallocate
memory to y and z? e.g.,

y = zeros(10000,1);
z = zeros(10000,1);

CS 175, Fall 2007: Professor Padhraic Smyth                Slide Set 2: MATLAB Programming 25
MATLAB Programming

• “M File” = text file with MATLAB code, e.g., sort.m

• Two kinds of M-files

– scripts
• no input arguments supplied
• no output arguments returned
• operates on data in workspace

– functions
• can accept input arguments and return output arguments
• internal variables local to function by default
• useful for extending functionality of MATLAB

CS 175, Fall 2007: Professor Padhraic Smyth                         Slide Set 2: MATLAB Programming 26
Example of a MATLAB script

%   script randscript
%   A simple script to generate a vector of n
%   random numbers. We calculate the numbers
%   using (a) for loops, and (b) a direct function call.
%
%                                       Professor Smyth, Oct 2007

Comment text: it is always
the top should clearly explain
what the script or function does

CS 175, Fall 2007: Professor Padhraic Smyth                                      Slide Set 2: MATLAB Programming 27
Example of a MATLAB script

%   script randsum
%   A simple script to generate a vector of n
%   random numbers. We calculate the numbers
%   using (a) for loops, and (b) a direct function call.
%
%                                       Professor Smyth, Oct 2007

n = 100000;    % the number of points for the "for loop”
y = zeros(n,1);   % preallocate memory for y
fprintf('Simulating %d random numbers.....\n\n',n);

Initialize various variables

Print out some information to the screen

CS 175, Fall 2007: Professor Padhraic Smyth                                        Slide Set 2: MATLAB Programming 28
Example of a MATLAB script
%   script randsum
%   A simple script to generate a vector of n
%   random numbers. We calculate the numbers
%   using (a) for loops, and (b) a direct function call.
%
%                                       Professor Smyth, Oct 2007

n = 100000;    % the number of points for the "for loop”
y = zeros(n,1);   % preallocate memory for y
fprintf('Simulating %d random numbers.....\n\n',n);

% first do the calculation using a "for loop"
fprintf('For loop calculations.....\n');        (1) Calculate the n random numbers
tic % set the timer
and their sum using a for loop,
for i=1:n
y(i) = rand(1);                              (2) record the time taken,
end                                             and (3) print to the screen
total = sum(y);
fprintf('Sum of %d random numbers = %f\n',n,total);
t1 = toc;   % read the time elapsed since "tic" (in seconds)
fprintf('Time taken, using for loop = %6.5f microseconds\n\n', (t1)*1000);

…...

CS 175, Fall 2007: Professor Padhraic Smyth                               Slide Set 2: MATLAB Programming 29
Example of a MATLAB script

………
…
% now do the calculation using vectorization
fprintf('Vectorization calculations.....\n');

tic % reset the timer
z = rand(n,1);
total = sum(z);

fprintf('Sum of %d random numbers = %f\n',n,total);
t2 = toc;   % read the time elapsed since "tic" (in seconds)
fprintf('Time taken, using vectorization = %6.5f microseconds\n', (t2)*1000);

(1) Now calculate n random numbers
and their sum using a direct function call
(2) record the time taken,
and (3) print to the screen

CS 175, Fall 2007: Professor Padhraic Smyth                                            Slide Set 2: MATLAB Programming 30
MATLAB random number generator

•     Function rand.m

•     Generates a sequence (of length n) of pseudorandom numbers:
– sequence generation: x(i) = mod(a * x(i-1), m)
– initialized with a state (“seed”) value for x(0)

CS 175, Fall 2007: Professor Padhraic Smyth                       Slide Set 2: MATLAB Programming 31
» help rand

RAND Uniformly distributed random numbers.

RAND produces pseudo-random numbers. The sequence of numbers
generated is determined by the state of the generator. Since MATLAB
resets the state at start-up, the sequence of numbers generated will
be the same unless the state is changed.

S = RAND('state') is a 35-element vector containing the current state
of the uniform generator. RAND('state',S) resets the state to S.
RAND('state',0) resets the generator to its initial state.
RAND('state',J), for integer J, resets the generator to its J-th state.
RAND('state',sum(100*clock)) resets it to a different state each time.

This generator can generate all the floating point numbers in the
closed interval [2^(-53), 1-2^(-53)]. Theoretically, it can generate
over 2^1492 values before repeating itself.

CS 175, Fall 2007: Professor Padhraic Smyth                              Slide Set 2: MATLAB Programming 32
Example of a MATLAB function

function [sum, difference] = sumdiff(a, b);

List of
input argument values,
Name of the    comma delimited
function       (any form of array
List of output                       data type)
Tells MATLAB this                   values returned
is a function                       (can be any form of
array data type)

CS 175, Fall 2007: Professor Padhraic Smyth                                Slide Set 2: MATLAB Programming 33
Example of a MATLAB function
function [sum, difference] = sumdiff(a, b);
% function [sum, difference] = sumdiff(a, b);
%
% A simple function to compute the sum and difference
% of two input arguments a and b
%
%                         Professor Smyth, Oct 2007
%
% INPUTS:
%           a: array of size r x c
%           b: array of size r x c
%
% OUTPUTS:
%    sum: a + b
%    difference: a - b

are very useful

Note the explicit statement explaining
what the inputs and outputs are
(including their dimensionality)

CS 175, Fall 2007: Professor Padhraic Smyth                      Slide Set 2: MATLAB Programming 34
Example of a MATLAB function
function [sum, difference] = sumdiff(a, b);
% function [sum, difference] = sumdiff(a, b);
%
% A simple function to compute the sum and difference
% of two input arguments a and b
%
%                         Professor Smyth, Oct 2007
%
……………..
Error checking is always a
% error checking
good idea!
[rowsa, colsa] = size(a);
[rowsb, colsb] = size(b);
if ( rowsa ~= rowsb ) | ( colsa ~= colsb)
error(‘sizes of a and b do not match’);
end

CS 175, Fall 2007: Professor Padhraic Smyth                     Slide Set 2: MATLAB Programming 35
Example of a MATLAB function
function [sum, difference] = sumdiff(a, b);
% function [sum, difference] = sumdiff(a, b);
%
% A simple function to compute the sum and difference
% of two input arguments a and b
%
%                         Professor Smyth, Oct 2007
%
……………..

% error checking
[rowsa, colsa] = size(a);
[rowsb, colsb] = size(b);
if ( rowsa ~= rowsb ) | ( colsa ~= colsb)
error(‘sizes of a and b do not match’);
end

sum = a + b;                          Finally, the actual computational
difference = a – b;                          part of the function

CS 175, Fall 2007: Professor Padhraic Smyth                      Slide Set 2: MATLAB Programming 36
MATLAB functions in general

• Function line definition
– required of all functions

• List of inputs and outputs
– comma delimited: [y, z] = average(a, b, c)
– for more than one output, outputs are enclosed in square brackets

• Input variables
– variables within function are local to the function
– input variables are readable to the function, but not writable
– values of returned arguments are passed back

• Search path
– MATLAB searches in this order:
• variable name, subfunction, current directory, MATLAB search
path

CS 175, Fall 2007: Professor Padhraic Smyth                             Slide Set 2: MATLAB Programming 37
Example of a MATLAB function

function [meanr, stdr, z] = simulate(n);

List of
input argument values,
Name of the    comma delimited
function       (any form of array
List of output                       data type)
Tells MATLAB this                   values returned
is a function                       (can be any form of
array data type)

CS 175, Fall 2007: Professor Padhraic Smyth                                Slide Set 2: MATLAB Programming 38
Example of a MATLAB function
function [meanr, stdr, z] = simulate(n);
% function [meanr, stdr, z] = simulate(n);
%
% A simple function to simulate a vector of n
% uniformly distributed random numbers and return the
% mean and standard deviation of the numbers.
%
%                         Professor Smyth, Oct 2007
%
% INPUTS:
%           n: number of random numbers generated (positive integer)
%
% OUTPUTS:
%    meanr: mean of the n random numbers
%    stdr: standard deviation of the random numbers
%    z:     an n x 1 array of random numbers

CS 175, Fall 2007: Professor Padhraic Smyth                     Slide Set 2: MATLAB Programming 39
Example of a MATLAB function
function [meanr, stdr, z] = simulate(n);
% function [meanr, stdr, z] = simulate(n);
%
% A simple function to simulate a vector of n
% uniformly distributed random numbers and return the
% mean and standard deviation of the numbers.
%
%                         Professor Smyth, Oct 2007
%
% INPUTS:
%           n: number of random numbers generated (positive integer)
%
% OUTPUTS:
%    meanr: mean of the n random numbers
%    stdr: standard deviation of the random numbers
%    z:     an n x 1 array of random numbers

% simple error checking to check n is a positive integer
if (rem(n,1)~=0) | n<=0
error('Input n must be a positive integer');
end

CS 175, Fall 2007: Professor Padhraic Smyth                      Slide Set 2: MATLAB Programming 40
Example of a MATLAB function
….
…

fprintf('Simulating %d random numbers.....\n\n',n);

% generate the n random numbers
z = rand(n,1);

% calculate the mean and standard deviation
meanr= mean(z);
fprintf('Mean of the %d random numbers = %f\n',n,meanr);
stdr= std(z);
fprintf('Standard deviation of the %d random numbers = %f\n',n,stdr);

Simulate the random numbers and
print out the results.

No need for an explicit return statement

Any values not returned are known only
locally to the function

CS 175, Fall 2007: Professor Padhraic Smyth                           Slide Set 2: MATLAB Programming 41
Creating a MATLAB function

In-class illustration of how to create and use a MATLAB function

CS 175, Fall 2007: Professor Padhraic Smyth                    Slide Set 2: MATLAB Programming 42
Calling the MATLAB function
» [m, s] = simulate(1000000);
Simulating 1000000 random numbers.....

Mean of the 1000000 random numbers = 0.499702
Standard deviation of the 1000000 random numbers = 0.499702
» [m, s] = simulate(1000000);
Simulating 1000000 random numbers.....

Mean of the 1000000 random numbers = 0.499684
Standard deviation of the 1000000 random numbers = 0.288456

»m
m = 0.4997

»s
s = 0.2885

CS 175, Fall 2007: Professor Padhraic Smyth                             Slide Set 2: MATLAB Programming 43
Another MATLAB function
function [meanr, stdr, z] = simplot(n,plotflag);
% function [meanr, stdr, z] = simplot(n,plotflag);
%
% A simple function to simulate a vector of n
% uniformly distributed random numbers and return the
% mean and standard deviation of the numbers. If
% plotflag is 1 a histogram of the numbers is plotted
%
%                         Professor Smyth, Oct 2007
%
% INPUTS:
%           n: number of random numbers generated (positive integer)
%   plotflag: if plotflag=1, a histogram of z is plotted,
%             otherwise no plotting
%
% OUTPUTS:
%    meanr: mean of the n random numbers
%    stdr: standard deviation of the random numbers
%    z:     an n x 1 array of random numbers

% simple error checking to check n is a positive integer
if (rem(n,1)~=0) | n<=0
error('Input n must be a positive integer');
end

CS 175, Fall 2007: Professor Padhraic Smyth                       Slide Set 2: MATLAB Programming 44
Simplot.m continued

fprintf('Simulating %d random numbers.....\n\n',n);

% generate the n random numbers
z = rand(n,1);

% calculate the mean and standard deviation
meanr= mean(z);
fprintf('Mean of the %d random numbers = %f\n',n,meanr);
stdr= std(z);
fprintf('Standard deviation of the %d random numbers = %f\n',n,stdr);

if nargin>1 & plotflag==1
figure                          Here is the new code.
hist(z, max(n/100,10))
end
Nargin is the number of input variables

If we have a 2nd input and it equals 1,
then we plot a histogram of the random numbers

syntax: hist(data vector, number of bins)

CS 175, Fall 2007: Professor Padhraic Smyth                            Slide Set 2: MATLAB Programming 45
Demonstration: plotting of sample mean as a function of n

• Extend simplot.m (call it simplot2.m)
– for      each value of i = 1 to n, calculate
•      mean(i) = [sum (x(i)…… x(i)) ]/I
•      use vectorization to do this
•      mean(i) should converge to the true mean 0.5 as i gets large
– why? “law of large numbers” from statistics

– illustration of the use of the online debugger

– we can plot this to visualize it

• grids, log axes, labels, titles

CS 175, Fall 2007: Professor Padhraic Smyth                               Slide Set 2: MATLAB Programming 46
Code that was added to simplot.m

if nargin>1 & plotflag==1
figure % figure for a histogram to see how uniform the numbers are
hist(z,max(n/100,10))

figure % figure to see visually how the sample mean converges to 0.5
cs = cumsum(z);     % generate a vector of cumulative sums
nvalues = 1:n;           % generate a vector of sample sizes
runningmean = cs./nvalues;     % there’s an error here (on purpose)
plot(nvaluess,runningmean);    % and another error here

grid;
axis([1 n 0 1]);
xlabel('Number of random numbers generated');
ylabel('Mean value');
title('Convergence of sample mean to true mean');

end

CS 175, Fall 2007: Professor Padhraic Smyth                         Slide Set 2: MATLAB Programming 47
Code that was added to simplot.m

if nargin>1 & plotflag==1
figure % figure for a histogram to see how uniform the numbers are
hist(z,max(n/100,10))

figure % figure to see visually how the sample mean converges to 0.5
cs = cumsum(z);     % generate a vector of cumulative sums
nvalues = 1:n;           % generate a vector of sample sizes
runningmean = cs./nvalues;     % there’s an error here (on purpose)
plot(nvaluess,runningmean);    % and another error here
%correct code:
%runningmean = cs./nvalues';
%plot(nvalues, runningmean);

grid;
axis([1 n 0 1]);
xlabel('Number of random numbers generated');
ylabel('Mean value');
title('Convergence of sample mean to true mean');

end

CS 175, Fall 2007: Professor Padhraic Smyth                         Slide Set 2: MATLAB Programming 48
Summary

•    Data Types
– arrays: char, numeric, struct, cell

•    Operators
– arithmetic, relational, logical

•    Flow Control
– conditionals, case, while, etc.

•    M-functions
– syntax
– examples of simple functions
– writing and debugging a simple MATLAB function

•    Code used in class is available on the class Web page

•    Next lecture:
– Classification algorithms

CS 175, Fall 2007: Professor Padhraic Smyth                            Slide Set 2: MATLAB Programming 49
Assignment 1

• Any questions?

CS 175, Fall 2007: Professor Padhraic Smyth   Slide Set 2: MATLAB Programming 50

```
To top