Docsity

MATLAB Tutorial 2-Machine Learning-Lecture Handout, Exercises of Machine Learning

Partial preview of the text

Download MATLAB Tutorial 2-Machine Learning-Lecture Handout and more Exercises Machine Learning in PDF only on Docsity!

Dr. Hanif Durad

2

Lecture Outline (1/2)

^

Script m-files^ 

Creating  Side effects ^

Function m-files^ 

Syntax of I/O parameters  Text output ^

Primary and secondary functions

^

Flow control^ 

Relational operators  Conditional execution of blocks  Loops

Dr. Hanif Durad

3

Lecture Outline (2/2)

^

Vectorization^ 

Using vector operations instead of loops  Preallocation of vectors and matrices  Logical and array indexing ^

Programming tricks^ 

Variable number of I/O parameters  Indirect function evaluation  Inline function objects  Global variables

Script Files

^

Not really programs^ 

No input/output parameters  Script variables are part of workspace ^

Useful for tasks that never change ^

Useful as a tool for documenting homework:^ 

Write a function that solves the problem for arbitrary parameters  Use a script to run function for specific parameters required by theassignment ^

Free Advice:^ 

Scripts offer no advantage over functions. ^

Functions have many advantages over scripts. ^

Always use functions instead of scripts.

Script to Plot

tan(

)^

Enter statements in file called tanplot.m1. Choose New... from File menu2. Enter lines listed belowContents of tanplot.m:

  1. Choose Save... from File menuSave as tanplot.m4. Run it>> tanplot

theta = linspace(1.6,4.6);tandata = tan(theta);plot(theta,tandata);xlabel('\theta (radians)');ylabel('tan(\theta)');grid on;axis([min(theta) max(theta) -5 5]);

Script Side-Effects (1/3)

^

All variables created in a script file are added to the workplace.This may have undesirable effects because ^

Variables already existing in the workspace may be overwritten ^

The execution of the script can be affected by the statevariables in the workspace.% easyplot: Script to plot data in file xy.dat% Load the dataD = load('xy.dat'); % D is a matrix with two columnsx = D(:,1); y = D(:,2); % x in 1st column, y in 2nd columnplot(x,y) % Generate the plot and label itxlabel('x axis, unknown units')ylabel('y axis, unknown units')title('Plot of generic x-y data set')

Script Side-Effects (2/3)

^

The easyplot script affects the workspace by creating three variables:

clear>> who(no variables show)>> easyplot>> whoYour variables are:D x

y

^

The D, x, and y variables are left in the workspace. These genericvariable names might be used in another sequence of calculations inthe same MATLAB session.

Function m-files (1/2)

^

Functions are subprograms:^ 

Functions use input and output parameters to communicate with otherfunctions and the command window  Functions use local variables that exist only while the function is executing.Local variables are distinct from variables of the same name in theworkspace or in other functions. ^

Input parameters allow the same calculation procedure (samealgorithm) to be applied to different data. Thus, function m-filesare reusable. ^

Functions can call other functions. ^

Specific tasks can be encapsulated into functions. This modularapproach enables development of structured solutions to complexproblems.

Function m-files (2/2)

Syntax:The first line of a function m-file has the form:function [outArgs] = funName(inArgs)outArgs are enclosed in [ ] ^

outrage is a comma-separated list of variable names ^

[ ] is optional if there is only one parameter ^

functions with no outArgs are legal inArgs are enclosed in ( ) ^

inArgs is a comma-separated list of variable names ^

functions with no inArgs are legal

Function Input and Output (2/7)

function twosum(x,y)% twosum Add two matrices% and print the resultx+y

twosum.m

function s = threesum(x,y,z)% threesum Add three variables% and return the results = x+y+z;

threesum.m

function [s,p] = addmult(x,y)% addmult Compute sum and product% of two matricess = x+y;p = x*y;

addmult.m

Function Input and Output Examples (3/7)Example: Experiments with twosum:>> twosum(2,2)ans =

4

x = [1 2]; y = [3 4];>> twosum(x,y)ans =^4

6

A = [1 2; 3 4]; B = [5 6; 7 8];

twosum(A,B);ans =

6

8 10

12

twosum('one','two')ans =

227

229

212

Notes:1. The result of the addition inside twosum is exposed because the x+y

expression does not end in a semicolon. (What if it did?)

  1. The strange results produced by twosum(’one’,’two’) are obtained by

adding the numbers associated with the ASCII character codes for eachof the letters in ‘one’ and ‘two’.Try double(’one’) and double(’one’) + double(’two’).

Example: Experiments withtwosum:

>> twosum((double('one')+double('one')),double('two'))ans =

Function Input and Output Examples (5/7)Example: Experiments with threesum:

a = threesum(1,2,3)a =

threesum(4,5,6)ans =

b= threesum(7,8,9);

Note: ^

The last statement produces no output because theassignment expression ends with a semicolon. The value of24 is stored in b.

Summary of Input and OutputParameters (7/7)

^

Values are communicated through input arguments andoutput arguments.

^

Variables defined inside a function are local to thatfunction. Local variables are invisible to other functionsand to the command environment.

^

The number of return variables should match thenumber of output variables provided by the function.This can be relaxed by testing for the number of returnvariables with

nargout

Text Input and Output

^

It is usually desirable to print results to the screen or to afile. On rare occasions it may be helpful to prompt theuser for information not already provided by the inputparameters to a function.

^

Inputs to functions:^ 

input

function can be used (and abused!).

^

Input parameters to functions are preferred.

^

Text output from functions:^ 

disp

function for simple output

^

fprintf

function for formatted output.