matlab tutorial - people.cs.pitt.edu

106
Matlab Tutorial Jeongmin Lee Computer Science Department University of Pittsburgh CS 1675 Intro to Machine Learning – Recitation

Upload: others

Post on 18-Dec-2021

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: matlab tutorial - people.cs.pitt.edu

MatlabTutorialJeongminLee

ComputerScienceDepartmentUniversityofPittsburgh

CS1675IntrotoMachineLearning– Recitation

Page 2: matlab tutorial - people.cs.pitt.edu

Acknowledgement

• SlidecontentsarebasedonMatlabtutorialbyMilosHauskrecht:http://people.cs.pitt.edu/~milos/courses/cs2750-Spring2018/Tutorial/

Page 3: matlab tutorial - people.cs.pitt.edu

Outline

• Part1.BasicsofMatlab• Part2.Input/Output• Part3.Operations• Part4.Matrixfunctions• Part5.Specialtopics

Page 4: matlab tutorial - people.cs.pitt.edu

Part1.BasicsofMatlab

• Variableassignment• IF/ELSE• Loops• Pause• Case• Script• Function• Help

Page 5: matlab tutorial - people.cs.pitt.edu

Variableassignment

• a=10• a=10;

• Assignmentwithsemicolon(;)suppressprintingoftheresult

Page 6: matlab tutorial - people.cs.pitt.edu

IF/ELSEcontrol

if a==4 %equalityconditionb=a^2;%asquared

elseif a~=10 %notequalb=a;

elseb=-a;

endend

• If/else/end• Useindentationtorepresentascope

Page 7: matlab tutorial - people.cs.pitt.edu

Loops(for)

for i=1:5i

end

• for{var}={start:end index}• {var}

• end

• Useindentation

Page 8: matlab tutorial - people.cs.pitt.edu

Loops(while)

while j>0j=j-1

end

Page 9: matlab tutorial - people.cs.pitt.edu

Casex=input('Value of x') % ask the inputswitch xcase {2,4}'X is even' %%% prints the stringcase {1,3} % Braces!!!'X is odd'case 0'X is zero'otherwise'Out of range'

end

Page 10: matlab tutorial - people.cs.pitt.edu

Scripts

• AnysyntacticallycorrectsequenceofMatlabcommands• Itcanbeexecutedbyspecifyingthenameofthescript(filesoftypexxx.m)

Page 11: matlab tutorial - people.cs.pitt.edu

Scripts

• Youcancreateyourownnewscript• New->Script• Then,writeyourowncode• Andsaveitwith“*.m”extension

Page 12: matlab tutorial - people.cs.pitt.edu

Scripts

• Youcanexecuteanyscriptbycallingthenameofthescriptfile

• Itshouldbeincurrentfolder

Page 13: matlab tutorial - people.cs.pitt.edu

Function

• Functionhasaspecificsyntaxandshouldbecalled• Itcanhavemorethanoneinputandoutputarguments• Normally,argumentsaretransferredbyvalue

function [x_squared, x_cubed]= tutorial_function(x)

x_squared=x^2;x_cubed=x_squared*x;

InputargumentOutputarguments

Page 14: matlab tutorial - people.cs.pitt.edu

Function

• Example• Savefollowingcontentasanewscript filetutorial_function.m

function [x_squared, x_cubed]= tutorial_function(x)

x_squared=x^2;x_cubed=x_squared*x;

Page 15: matlab tutorial - people.cs.pitt.edu

Function

• Example• Youcanrunthefunctionlikefollowing:

Page 16: matlab tutorial - people.cs.pitt.edu

Help

• Youcangetreferenceaboutanyfunctionwith>>help function_name

Page 17: matlab tutorial - people.cs.pitt.edu

Help

• Evenafunctionwedefined,wecanseeitscontents>>help tutorial_function

Page 18: matlab tutorial - people.cs.pitt.edu

Part2.InputsandOutputs

• Getuserinput• Saveresults• Deleteallvariables• Loadresults

Page 19: matlab tutorial - people.cs.pitt.edu

Getuserinput

• >>x=input('Explanationforuser:');• Willgetuserinputandinsertintovariablex

Page 20: matlab tutorial - people.cs.pitt.edu

Getuserinput

• Whenyouneedstring asinput,add‘s’• >>y=input(‘Gimme astring:’,’s’);

Page 21: matlab tutorial - people.cs.pitt.edu

Savecurrentresults(=variable)

• Youcansaveresultstoaascii file• It(ascii)means,youcanreadthefilefromanytexteditor• (LetssayWisaanyvariable)• >>saveascii_file_name W –ascii

Page 22: matlab tutorial - people.cs.pitt.edu

Savecurrentresults(=variable)

• Youcanalsosaveresultsintoabinaryfile• BinaryisaMatlab-specificform• >>savebinary_file_nameW

Page 23: matlab tutorial - people.cs.pitt.edu

Savecurrentresults(=variable)

• TosaveALLvariables,writeonlyafilename• >>savebinary_file_name1

Page 24: matlab tutorial - people.cs.pitt.edu

Deletevariables

• Todeleteavariableinworkingmemory:• >>clearvariable_name

• TodeleteALLvariableinworkingmemory:• >>clearall

Page 25: matlab tutorial - people.cs.pitt.edu

Loadvariables

• Loadallvariablesfromabinaryfile• >>loadbinary_file_name

• Loadaspecificvariablefromabinaryfile• >>loadbinary_file_name W

Page 26: matlab tutorial - people.cs.pitt.edu

Loadvariables

• LoadfromanASCIIfile• (notethatwhenadataisnotinmatrixform,youneedyourownprogramusingscanf functions)• >>loadascii_file_name• >> W=ascii_file_name

Page 27: matlab tutorial - people.cs.pitt.edu

Part3.Operations

• Scalarop• Vectorop•Matrixop• Vectorandconstantop•Matrixandvector

Page 28: matlab tutorial - people.cs.pitt.edu

Scalaroperations

• Shouldbestraightforwardx=13; y=7;x-yx+yx*yx/y

Page 29: matlab tutorial - people.cs.pitt.edu

Scalaroperations

• Mod:modulusmod(x,y)x=12.5ceil(x)floor(x)round(x)sin(x)cos(y)

Page 30: matlab tutorial - people.cs.pitt.edu

Vectoroperations

• ‘ :transposerow_vector=[1234]column_vector=[4567]’column_vector2=[4; 5; 6; 7]

Creation

Page 31: matlab tutorial - people.cs.pitt.edu

Vectoroperations

>>length(row_vector)>>length(column_vector)

>>size(row_vector)>>size(column_vector)

Length:givesnumberofelementsinavectorSize:givesdimensionality

Page 32: matlab tutorial - people.cs.pitt.edu

Vectoroperations

>>d=row_vector *column_vector

Innerproduct:vec1*vec2- Theyshouldhavesamelength

Page 33: matlab tutorial - people.cs.pitt.edu

Matrixoperations

A=[123; 456; 789]

B=[12-1-223]

Creation

Page 34: matlab tutorial - people.cs.pitt.edu

Matrixoperations

size(B) %full size

size(A,1)%num ofrows

size(A,2)%num ofcols

Size

Page 35: matlab tutorial - people.cs.pitt.edu

Matrixoperations

C=A*B

Multiplication

• Matrixmultiplicationispossibleonlywhensize(A,2)==size(B,1)• Resultisamatrixsize(A,1)xsize(B,2) A’#ofcols==B’s#ofrows

Page 36: matlab tutorial - people.cs.pitt.edu

Matrixoperations

A3=A(:,3)

Select3rd columnofamatrix

Page 37: matlab tutorial - people.cs.pitt.edu

MatrixoperationsSelectthefirstrow

A1=A(1,:)

Page 38: matlab tutorial - people.cs.pitt.edu

MatrixoperationsSelectasubmatrix

AAAA=A(1:2,1:2)

Page 39: matlab tutorial - people.cs.pitt.edu

Element-wiseop.Element-wisemultiplication

D=[123;456]E=[1 2 3

4 5 6]

F=D.*E

Page 40: matlab tutorial - people.cs.pitt.edu

Element-wiseop.Element-wisedivisionofvectors

a=[1 2 3 4]b=[1 3 5 9]

c=a./b

Page 41: matlab tutorial - people.cs.pitt.edu

Element-wiseop.Element-wisesquare

D.^2

Page 42: matlab tutorial - people.cs.pitt.edu

Vectorandconstant

visvector,cisscalar

v=[1234]c=2

Page 43: matlab tutorial - people.cs.pitt.edu

Vectorandconstant

Whenconstantisadded/substracted tothevector, itisadded / substracted fromEACHelement

v-cv+c

Page 44: matlab tutorial - people.cs.pitt.edu

Vectorandconstant

Constantcansimplymultiplyordivideavector

v/cv*c

Page 45: matlab tutorial - people.cs.pitt.edu

Vectorandconstant

Howeveronlyc./v isdefinedandgives[c/v(1)...c/v(length(v))

c./v

Page 46: matlab tutorial - people.cs.pitt.edu

Matrixandvector

Forthispurposes,wedefineavectoras2Dmatrixwithonedimensionequalto1.

x=[123]'%remember' meanstranspose

Page 47: matlab tutorial - people.cs.pitt.edu

Matrixandvector

Multiplication

x=[123]'A=[1-23;012;001]

b=A*x

Page 48: matlab tutorial - people.cs.pitt.edu

Matrixandvector

Matrixinversionorhowtosolvelinearsystem

x_solved=inv(A)*b :equationAx=b; solvedx=inv(A)b

Page 49: matlab tutorial - people.cs.pitt.edu

Matrixandvector

Solvingasystemoflinearequations inanotherway

x_solved_another_way=A\b (\ : backslash)

Page 50: matlab tutorial - people.cs.pitt.edu

Matrixandvector

Theapplicationofmatrixcomputationforlinearregression

x = rand(1,100)xDumb = [ones(1,100);x]A= [12]y = A * xDumb + randn(1,100) * 0.1;

A_solved = y / xDumb

• bias and slope parametersofalinearmodel

• y=1+2x+random_noise• performs linearregression,

leastsquares solution ofoverdetermined system!

Page 51: matlab tutorial - people.cs.pitt.edu

Matrixandvector

Theapplicationofmatrixcomputationforlinearregression

x = rand(1,100)xDumb = [ones(1,100);x]A= [12]y = A * xDumb + randn(1,100) * 0.1;

A_solved = y / xDumb

Page 52: matlab tutorial - people.cs.pitt.edu

Part4.Matrixfunctions

• Squarerootsofelementsofamatrix• Aggregatefunctions• Specialmatrices• Transformmatrices•Multidimensionalarrays• Structures

Page 53: matlab tutorial - people.cs.pitt.edu

Squareroots

Squarerootsofeachelementsofamatrix

F=[149;162536]

F_= sqrt(F)

Page 54: matlab tutorial - people.cs.pitt.edu

Aggregate:Sum

Aggregateelementsbysummingoperation

A=[1234;5678;9101112]

Page 55: matlab tutorial - people.cs.pitt.edu

Aggregate:Sum

Summationperformedbyfirst index(sumsofcolumns)

A=[1234;5678;9101112]

sum(A)

Page 56: matlab tutorial - people.cs.pitt.edu

Aggregate:Sum

Summationperformedbysecondindex(sumsofrows)

A=[1234;5678;9101112]

sum(A, 2)

Page 57: matlab tutorial - people.cs.pitt.edu

Aggregate:Sum

Sumofthewholematrix

A=[1234;5678;9101112]

sum(sum(A))

Page 58: matlab tutorial - people.cs.pitt.edu

Aggregate:Product

Productperformedbyfirst index(productofcolumns)

A=[1234;5678;9101112]

prod(A)

Page 59: matlab tutorial - people.cs.pitt.edu

Aggregate:Product

Productperformedbysecondindex(productofrows)

A=[1234;5678;9101112]

product(A, 2)

Page 60: matlab tutorial - people.cs.pitt.edu

Aggregate:Product

Productofthewholematrix

A=[1234;5678;9101112]

product(product(A))

Page 61: matlab tutorial - people.cs.pitt.edu

Aggregate:MeansandStandardDeviations

Meanbyfirst index(meanofcolumns)

mean_A_column=mean(A)

Page 62: matlab tutorial - people.cs.pitt.edu

Aggregate:MeansandStandardDeviations

Meanbysecondindex(meanofrows)

mean_A_row=mean(A,2)

Page 63: matlab tutorial - people.cs.pitt.edu

Aggregate:MeansandStandardDeviations

Standarddeviationbyfirst index(s.d. ofcolumns)

std_A_column=std(A)

Page 64: matlab tutorial - people.cs.pitt.edu

Aggregate:MeansandStandardDeviations

Standarddeviationbysecondindex(s.d. ofrows)

std_A_row=std(A,[],2)

[]MUSTbehere

Page 65: matlab tutorial - people.cs.pitt.edu

Specialmatrices

Diagonalmatrix

diagonal_matrix=diag([1234])

Page 66: matlab tutorial - people.cs.pitt.edu

Specialmatrices

Zeromatrix

all_zeros=zeros(3,4)

Page 67: matlab tutorial - people.cs.pitt.edu

Specialmatrices

Onematrix

all_ones=ones(4,2)

Page 68: matlab tutorial - people.cs.pitt.edu

Specialmatrices

Unitmatrix

unit_matrix=eye(4)

Page 69: matlab tutorial - people.cs.pitt.edu

Transformofmatrix

Matrix(array)repetition

v=[123];

V1=repmat(v,3,1)

Numberofrowrepetition

Numberofcolrepetition

Page 70: matlab tutorial - people.cs.pitt.edu

Transformofmatrix

Matrix(array)repetition

v=[123];

V2=repmat(v,1,3)

Numberofrowrepetition

Numberofcolrepetition

Page 71: matlab tutorial - people.cs.pitt.edu

Transformofmatrix

Matrix(array)repetition

v_tran=v';vv_tran=repmat(v_tran,3,1)

Page 72: matlab tutorial - people.cs.pitt.edu

Transformofmatrix

Matrix(array)reshape

A=[123456789101112];

A_matrix=reshape(A,3,4)

3*4=length(A),i.e.totalnumberofelementsmustnotchange

Page 73: matlab tutorial - people.cs.pitt.edu

Transformofmatrix

Multidimensionalarrays

MX=zeros(3,3,3)

Page 74: matlab tutorial - people.cs.pitt.edu

Transformofmatrix

Multidimensionalarrays

A=[123456789101112];

MX=reshape(A,2,3,2)

2*3*2=length(A),i.e.totalnumberofelementsmustnotchange

Page 75: matlab tutorial - people.cs.pitt.edu

StructuresStructureisanobjectwithaccessibleattributesbyitsname

weather=struct('temp',72,'rainfall',0.0)

weather.temp

Page 76: matlab tutorial - people.cs.pitt.edu

Structures

Initialize3rd elementofweatherarray

weather(3)=struct('temp',72,'rainfall',0.0)

Page 77: matlab tutorial - people.cs.pitt.edu

Structures

createsweathermatrixwiththesameinitialvalues

weather=repmat(struct('temp',72,'rainfall',0.0),1,3)

Page 78: matlab tutorial - people.cs.pitt.edu

CellStructures

Cellcancontainmultipleelementswithdifferenttypes

A ={[143;058;729], 'AnneSmith'; 3+7i, -pi:pi/4:pi}

Page 79: matlab tutorial - people.cs.pitt.edu

CellStructures

A(1):accesscellelement

A{1}:returnscontents acellelement

Page 80: matlab tutorial - people.cs.pitt.edu

Part5.Specialtopics

• Howtoplotresults• Findfunction• Sortfunction• Randomnumbergeneratorsandhistograms• Randommatrices

Page 81: matlab tutorial - people.cs.pitt.edu

PlotResults

Preparedata

A=[1234579];B=[1213141411108];

Page 82: matlab tutorial - people.cs.pitt.edu

PlotResults

Plottwovectorsinsamelength

plot(A,B);

Page 83: matlab tutorial - people.cs.pitt.edu

PlotResults

Retainpreviousfigureandaddnewgraphonit

C=B-4;Holdon;plot(A,C,'*-r')

Newlinewithreadcolorandhasstarsandlines

Retainoldgraph

Page 84: matlab tutorial - people.cs.pitt.edu

PlotResults

Addlabel,title,andlegend

xlabel('Month')ylabel('Powerconsumption')title('Thisisdemograph')legend('NewYork','Pittsburgh')

Page 85: matlab tutorial - people.cs.pitt.edu

PlotResults

Createnewplot(holdoff)

holdoff;plot(A,C./B);title('Consumptionratio')

Page 86: matlab tutorial - people.cs.pitt.edu

PlotResults

Opennewplot(figure;)

figure;C=eye(10,10);imagesc(C);title('Thewaytoplotmatrices')

imagesc:displayimage(matrix)withscaledcolors

Page 87: matlab tutorial - people.cs.pitt.edu

PlotResults

Let’splota3Dplot

[XY]=meshgrid(-pi:pi/10:pi,-pi:pi/10:pi);Z=sin(2*X).*cos(3*Y);surf(X,Y,Z);

meshgrid:gridtocomputefunctioninevenintervalssurf:plots3dfunction

Page 88: matlab tutorial - people.cs.pitt.edu

PlotResults

2Dplotofthesamefunction

imagesc(Z);colorbar

Page 89: matlab tutorial - people.cs.pitt.edu

PlotResults

Plot3Dtrajectory

t=0:0.1:5;x=sin(pi*t)+0.1*t;y=cos(pi*t)-0.2*t;z=2*t;

plot3(x,y,z,'d:m');gridonxlabel('x')ylabel('y')zlabel('z')

showsmagentadiamondsinadditiontodottedline

Page 90: matlab tutorial - people.cs.pitt.edu

Find

Pickscomponentssatisfyingacondition

a=[12345];

find(a>2)

Outputsareindicesthatcorrespondtovaluesofvectorthatsatisfythepredicate(a>2)

Page 91: matlab tutorial - people.cs.pitt.edu

FindandReplace

e.g.,Replacesallvalueslargerthan0.6with1

some_probability_vector=[0.20.70.40.60.120.440.72];

some_probability_vector(find(some_probability_vector>0.6))=1

Page 92: matlab tutorial - people.cs.pitt.edu

Sortfunction

Let’ssaywehavestudentsidsandcorrespondingscores

scores=[9455231210];students=[102232343242343451223232];

Page 93: matlab tutorial - people.cs.pitt.edu

Sortfunction

Studentpointssortedaccordingtotheresultsontest

[scores,index]=sort(scores);

Page 94: matlab tutorial - people.cs.pitt.edu

Sortfunction

Reorderstudentidsbytheindexfromsortfunction

B=B(index)

Page 95: matlab tutorial - people.cs.pitt.edu

Sortfunction

Let’ssortrowsorcolumnsofmatrices

A=[123; 1098; 567]

Page 96: matlab tutorial - people.cs.pitt.edu

Sortfunction

Eachcolumnisindependentlysorted

sort(A,1)

Page 97: matlab tutorial - people.cs.pitt.edu

Sortfunction

Eachrowisindependentlysorted

sort(A,2)

Page 98: matlab tutorial - people.cs.pitt.edu

Randomnumbergenerator

RandomvectorsfromNormal(Gaussian)distribution

normal_vector=randn(1000,1);

Numberofrow

Numberofcol

Page 99: matlab tutorial - people.cs.pitt.edu

Randomnumbergenerator

Createhistogramofrandomnumbers

normal_vector=randn(1000,1);hist(normal_vector,20)title('Normaldistribution')

20:numberofbinsinhistogram

Page 100: matlab tutorial - people.cs.pitt.edu

Randomnumbergenerator

RandomvectorsfromUniformdistribution

uniform_vector=rand(1000,1);

Numberofrow

Numberofcol

Page 101: matlab tutorial - people.cs.pitt.edu

Randomnumbergenerator

Createhistogramofrandomnumbers

uniform_vector=rand(1000,1);hist(uniform_vector,20)title('Uniformdistribution')

20:numberofbinsinhistogram

Page 102: matlab tutorial - people.cs.pitt.edu

Randomnumbergenerator

Createhistogramofrandomnumbers

uniform_vector=rand(1000,1);hist(uniform_vector,20)title('Uniformdistribution')

20:numberofbinsinhistogram

Page 103: matlab tutorial - people.cs.pitt.edu

Randomnumbergenerator

Histogramofrandomvectorfromchi-squaredistribution

chi_square_vector_df3=chi2rnd(3,1000,1)hist(chi_square_vector_df3,20)title('\chi^{2}distribution')

20:numberofbinsinhistogram

Page 104: matlab tutorial - people.cs.pitt.edu

Generaterandompermutation

fori=1:3A=randperm(10)

end

Page 105: matlab tutorial - people.cs.pitt.edu

Generaterandommatrices

A=randn(128,64);

subplot(1,2,1),imagesc(A),title('Originalimage')B=[111;111;111]/9;A=filter2(B,A);subplot(1,2,2),imagesc(A),title('Smoothedrandomimage')

filter2:functionfor2-dimensionalfiltering(justforillustration,heresmoothstheimage)

Page 106: matlab tutorial - people.cs.pitt.edu

Thanks!-

Questions?