42
Quick introduction to Matlab PASCAL Bootcamp in Machine Learning - 2007

Short Matlab

Embed Size (px)

Citation preview

Page 1: Short Matlab

Quick introductionto Matlab

PASCAL Bootcamp in Machine Learning -2007

Page 2: Short Matlab

Outline

Matlab introductionMatlab elements

TypesVariablesMatrices

Loading, saving and plotingMatlab Programming languageScripts and functions

Page 3: Short Matlab

Matlab introduction

Matlab is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrixLABoratory.Matlab is also a programming language that currently is widely used as a platform for developing tools for Machine Learning

Page 4: Short Matlab

Matlab introduction

Why it is useful for prototyping AI projects:large toolbox of numeric/image library functionsvery useful for displaying, visualizing datahigh-level: focus on algorithm structure, not on low-level details allows quick prototype development of algorithms

Page 5: Short Matlab

Matlab introduction

Some other aspects of MatlabMatlab is an interpreter -> not as fast as compiled code

Typically quite fast for an interpreted languageOften used early in development -> can then convert to C (e.g.,) for speed

Can be linked to C/C++, JAVA, SQL, etcCommercial product, but widely used in industry and academia

Many algorithms and toolboxes freely available

Page 6: Short Matlab

Opening Matlab

CommandWindow

WorkingMemory

CommandHistory

WorkingPath

Page 7: Short Matlab

Data Types

Page 8: Short Matlab

Variables

Have not to be previously declaredVariable names can contain up to 63 charactersVariable names must start with a letter followed by letters, digits, and underscores.Variable names are case sensitive

Page 9: Short Matlab

Matlab Special Variablesans Default variable name for resultspi Value of πeps Smallest incremental numberinf InfinityNaN Not a number e.g. 0/0realmin The smallest usable positive real numberrealmax The largest usable positive real number

Page 10: Short Matlab

Matlab Assignment & Operators

Assignment = a = b (assign b to a)Addition + a + bSubtraction - a - bMultiplication * or.* a*b or a.*bDivision / or ./ a/b or a./bPower ^ or .^ a^b or a.^b

Page 11: Short Matlab

Matlab MatricesMatlab treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored. Vectors are special forms of matrices and contain only one row OR one column.Scalars are matrices with only one row AND one column

Page 12: Short Matlab

Matlab MatricesA 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

Page 13: Short Matlab

Matlab MatricesA 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 =

1345-2

Page 14: Short Matlab

Matlab MatricesA 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 34 5 67 8 9

Page 15: Short Matlab

Extracting a Sub-MatrixA 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.

Page 16: Short Matlab

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

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

matrix =1 2 34 5 67 8 9

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

» col_two=matrix( : , 2)

col_two =258

Page 17: Short Matlab

Matlab Matrices

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

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

matrix =1 2 34 5 67 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=matrix(2 : 2 , 1 : 3)

rowvec =4 5 6

Page 18: Short Matlab

Colon Operator

is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) fills A, preserving its shape from before. In this case, the right side must contain the same number of elements as A.

A(:)

is a vector in four-dimensional array A. The vector includes A(i,j,k,1),A(i,j,k,2), A(i,j,k,3), and so on.

A(i,j,k,:)is the k-th page of three-dimensional array A.A(:,:,k)is A(:,j), A(:,j+1),...,A(:,k)A(:,j:k)is A(j), A(j+1),...,A(k)A(j:k)

is the equivalent two-dimensional array. For matrices this is the same as A.A(:,:)is the i-th row of AA(i,:)is the j-th column of AA(:,j)

is the same as [j,j+i,j+2i, ..,k] is empty if i > 0 and j > k or if i < 0 and j < kj:i:kis the same as [j,j+1,...,k] is empty if j > kj:k

Page 19: Short Matlab

Matlab MatricesAccessing Single Elements of a Matrix A(i,j)Accessing Multiple Elements of a MatrixA(1,4) + A(2,4) + A(3,4) + A(4,4) sum(A(1:4,4)) or

sum(A(:,end))The keyword end refers to the last row or column. Deleting Rows and Columnsto delete the second column of X, useX(:,2) = [] Concatenating Matrices A and BC=[A;B]

Page 20: Short Matlab

Some matrixfunctions in Matlab

X = ones(r,c) % Creates matrix full with onesX = zeros(r,c) % Creates matrix full with zerosA = diag(x) % Creates squared matrix with

vector x in diagonal[r,c] = size(A) % Return dimensions of matrix A+ - * / % Standard operations.+ .- .* ./ % Wise addition, substraction,…v = sum(A) % Vector with sum of columns

Page 21: Short Matlab

Some powerful matrixfunctions in Matlab

X = A’ % Transposed matrixX = inv(A) % Inverse matrix squared matrixX = pinv(A) % Pseudo inverseX = chol(A) % Cholesky decomp.d = det(A) % Determinant[X,D] = eig(A) % Eigenvalues and eigenvectors[Q,R] = qr(X) % QR decomposition[U,D,V] = svd(A) % singular value decomp.

Page 22: Short Matlab

Sava data in files

save myfile VAR1 VAR2 …orsave(‘myfile’,’VAR1’,’var2’)

Page 23: Short Matlab

Load data from files

Loadload filenameload ('filename')load filename.extload filename -asciiload filename -mat

File Formatsmat -> Binary MAT-file formascii -> 8-digit ASCII formascii–tabs Delimit array elements with tabs

Page 24: Short Matlab

Plotting with MatlabMatlab has a lot of function for plotting data. The basic one will plot one vector vs. another. The first one will be treated as the abscissa (or x) vector and the second as the ordinate (or y) vector. The vectors have to be the same length.

>> plot (time, dist) % plotting versus time

Matlab will also plot a vector vs. its own index. The index will be treated as the abscissa vector. Given a vector “time” and a vector “dist” we could say:

>> plot (dist) % plotting versus index

Page 25: Short Matlab

Plotting with Matlab

» a = 1:100;» b = 100:0.01:101;» c = 101:-1:1;» d = [a b c];» e = [d d d d d];» plot(e)

0 200 400 600 800 1000 1200 1400 16000

20

40

60

80

100

120

Page 26: Short Matlab

Plotting with Matlab

» x = rand(1,100);» y = rand(1,100);» plot(x,y,'*')

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

Page 27: Short Matlab

Plotting with Matlab

There are commands in Matlab to "annotate" a plot to put on axis labels, titles, and legends. For example:

>> % To put a label on the axes we would use:>> xlabel ('X-axis label')>> ylabel ('Y-axis label')

>> % To put a title on the plot, we would use:>> title ('Title of my plot')

Page 28: Short Matlab

Plotting with Matlab

Vectors may be extracted from matrices. Normally, we wish to plot one column vs. another. If we have a matrix “mydata” with two columns, we can obtain the columns as a vectors with the assignments as follows:

>> first_vector = mydata ( : , 1) ; % First column>> second_vector = mydata ( : , 2) ; % Second one>>% and we can plot the data>> plot ( first_vector , second_vector )

Page 29: Short Matlab

Matlab programming language

Elements of Matlab as a programming language:

ExpressionsFlow Control blocks

ConditionalIterations

ScriptsFunctions

Page 30: Short Matlab

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

Page 31: Short Matlab

Expressions: Matlab Logical Operators

MATLAB supports three logical operators.not ~ % highest precedenceand & % equal precedence with oror | % equal precedence with and

Page 32: Short Matlab

Expressions: Matlab Logical Functions

MATLAB also supports some logical functions.

any (x) returns 1 if any element of x is nonzeroall (x) returns 1 if all elements of x are nonzeroisnan (x) returns 1 at each NaN in xisinf (x) returns 1 at each infinity in xfinite (x) returns 1 at each finite value in x

Page 33: Short Matlab

Matlab Conditional Structures

a = input(‘valor1? ‘); b = input(‘valor2? ‘);if a == b,

fprintf(‘a is equal to b\n’);elseif a > 0 && b > 0

fprintf(‘both positive\n’);else

fprintf(‘other case\n’);end

if expression cond.

sentences

elseif expr. cond.

sentences

else

sentences

end

Page 34: Short Matlab

Matlab Iteration Structures (I)

M = rand(10,10); suma = 0;for i = {2,5:8} % files 2, 5, 6, 7 i 8for j = {1:5,8:9} % rows 1, 2, 3, 4, 5, 8, 9suma = suma + M(i,j);

endendfprintf(‘sum = %d\n’,suma);

M = rand(4,4); suma = 0;for i = 1:4for j = 1:4suma = suma + M(i,j);

endendfprintf(‘sum = %d\n’,suma);

for variable = exprsentence;...sentence;

end

Page 35: Short Matlab

Matlab Iteration Structures (II)

while exprsentence;...sentence;

end

M = rand(4,4);i = 1; j = 1; suma = 0;

while i <= 4while j <= 4suma = suma + M(i,j);j = j+1;

endi = i+1;

end

fprintf(‘suma = %f\n’,suma);

Page 36: Short Matlab

Loops should be avoided when possible:

for ind = 1:10000b(ind)=sin(ind/10)

end

Alternatives:

x=0.1:0.1:1000; b=sin(x);

Most of the loops can be avoided!!!

(Optimizing code: vectorization)

x=1:10000;b=sin(x/10);

Page 37: Short Matlab

Text files containing Matlab programs. Can be called form the command line or fromother M-filesPresent “.m” extensionTwo kind of M-files:

ScriptsFunctions

M-files

Page 38: Short Matlab

M-files: Scripts

Without input arguments, they do not returnany value.

Page 39: Short Matlab

M-files: Script Example

x = [4 3 2 10 -1];n = length(x); suma1 = 0; suma2 = 0;for i=1:n

suma1 = suma1 + x(i); suma2 = suma2 + x(i)*x(i);

endpromig = suma1/n;desvia = sqrt(suma2/n – promig*promig);

1) >> edit estadistica.m2) Write into the editor:

3) Save the file4) >> run estadistica5) >> promig, desviapromig = 3.6000desvia = 3.6111

Page 40: Short Matlab

M-files: FunctionsWith parameters and returning valuesOnly visible variables defined inside the function orparametersUsually one file for each function definedStructure:

function [out1, out2, ..., outN] = name-function (par1, par2, ..., parM)sentence;….sentence;

end

Page 41: Short Matlab

M-files: Functions Example1) >> edit festadistica.m2) Write into the editor:

3) Save the file4) >> edit sumes.m5) Write into the editor:

6) Save the file7) >> [p,d] = festadistica([4 3 2 10 -1])p = 3.6000d = 3.6111

function [promig,desvia] = festadistica(x)n = length(x);[suma1,suma2] = sumes(x,n);promig = suma1/n;desvia = sqrt(suma2/n – promig*promig);end

function [sy1,sy2] = sumes(y,m)sy1 = 0; sy2 = 0;for i=1:m

sy1 = sy1 + y(i); % suma yisy2 = sy2 + y(i)*y(i); % suma yi^2

endend

Page 42: Short Matlab

Within MatlabType help at the Matlab prompt or help followed by a function name for help on a specific function

OnlineOnline documentation for Matlab at the MathWorks website

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html

There are also numerous tutorials online that are easily found with a web search.

Help