matlab tutorial - people.cs.pitt.edu
TRANSCRIPT
MatlabTutorialJeongminLee
ComputerScienceDepartmentUniversityofPittsburgh
CS1675IntrotoMachineLearning– Recitation
Acknowledgement
• SlidecontentsarebasedonMatlabtutorialbyMilosHauskrecht:http://people.cs.pitt.edu/~milos/courses/cs2750-Spring2018/Tutorial/
Outline
• Part1.BasicsofMatlab• Part2.Input/Output• Part3.Operations• Part4.Matrixfunctions• Part5.Specialtopics
Part1.BasicsofMatlab
• Variableassignment• IF/ELSE• Loops• Pause• Case• Script• Function• Help
Variableassignment
• a=10• a=10;
• Assignmentwithsemicolon(;)suppressprintingoftheresult
IF/ELSEcontrol
if a==4 %equalityconditionb=a^2;%asquared
elseif a~=10 %notequalb=a;
elseb=-a;
endend
• If/else/end• Useindentationtorepresentascope
Loops(for)
for i=1:5i
end
• for{var}={start:end index}• {var}
• end
• Useindentation
Loops(while)
while j>0j=j-1
end
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
Scripts
• AnysyntacticallycorrectsequenceofMatlabcommands• Itcanbeexecutedbyspecifyingthenameofthescript(filesoftypexxx.m)
Scripts
• Youcancreateyourownnewscript• New->Script• Then,writeyourowncode• Andsaveitwith“*.m”extension
Scripts
• Youcanexecuteanyscriptbycallingthenameofthescriptfile
• Itshouldbeincurrentfolder
Function
• Functionhasaspecificsyntaxandshouldbecalled• Itcanhavemorethanoneinputandoutputarguments• Normally,argumentsaretransferredbyvalue
function [x_squared, x_cubed]= tutorial_function(x)
x_squared=x^2;x_cubed=x_squared*x;
InputargumentOutputarguments
Function
• Example• Savefollowingcontentasanewscript filetutorial_function.m
function [x_squared, x_cubed]= tutorial_function(x)
x_squared=x^2;x_cubed=x_squared*x;
Function
• Example• Youcanrunthefunctionlikefollowing:
Help
• Youcangetreferenceaboutanyfunctionwith>>help function_name
Help
• Evenafunctionwedefined,wecanseeitscontents>>help tutorial_function
Part2.InputsandOutputs
• Getuserinput• Saveresults• Deleteallvariables• Loadresults
Getuserinput
• >>x=input('Explanationforuser:');• Willgetuserinputandinsertintovariablex
Getuserinput
• Whenyouneedstring asinput,add‘s’• >>y=input(‘Gimme astring:’,’s’);
Savecurrentresults(=variable)
• Youcansaveresultstoaascii file• It(ascii)means,youcanreadthefilefromanytexteditor• (LetssayWisaanyvariable)• >>saveascii_file_name W –ascii
Savecurrentresults(=variable)
• Youcanalsosaveresultsintoabinaryfile• BinaryisaMatlab-specificform• >>savebinary_file_nameW
Savecurrentresults(=variable)
• TosaveALLvariables,writeonlyafilename• >>savebinary_file_name1
Deletevariables
• Todeleteavariableinworkingmemory:• >>clearvariable_name
• TodeleteALLvariableinworkingmemory:• >>clearall
Loadvariables
• Loadallvariablesfromabinaryfile• >>loadbinary_file_name
• Loadaspecificvariablefromabinaryfile• >>loadbinary_file_name W
Loadvariables
• LoadfromanASCIIfile• (notethatwhenadataisnotinmatrixform,youneedyourownprogramusingscanf functions)• >>loadascii_file_name• >> W=ascii_file_name
Part3.Operations
• Scalarop• Vectorop•Matrixop• Vectorandconstantop•Matrixandvector
Scalaroperations
• Shouldbestraightforwardx=13; y=7;x-yx+yx*yx/y
Scalaroperations
• Mod:modulusmod(x,y)x=12.5ceil(x)floor(x)round(x)sin(x)cos(y)
Vectoroperations
• ‘ :transposerow_vector=[1234]column_vector=[4567]’column_vector2=[4; 5; 6; 7]
Creation
Vectoroperations
>>length(row_vector)>>length(column_vector)
>>size(row_vector)>>size(column_vector)
Length:givesnumberofelementsinavectorSize:givesdimensionality
Vectoroperations
>>d=row_vector *column_vector
Innerproduct:vec1*vec2- Theyshouldhavesamelength
Matrixoperations
A=[123; 456; 789]
B=[12-1-223]
Creation
Matrixoperations
size(B) %full size
size(A,1)%num ofrows
size(A,2)%num ofcols
Size
Matrixoperations
C=A*B
Multiplication
• Matrixmultiplicationispossibleonlywhensize(A,2)==size(B,1)• Resultisamatrixsize(A,1)xsize(B,2) A’#ofcols==B’s#ofrows
Matrixoperations
A3=A(:,3)
Select3rd columnofamatrix
MatrixoperationsSelectthefirstrow
A1=A(1,:)
MatrixoperationsSelectasubmatrix
AAAA=A(1:2,1:2)
Element-wiseop.Element-wisemultiplication
D=[123;456]E=[1 2 3
4 5 6]
F=D.*E
Element-wiseop.Element-wisedivisionofvectors
a=[1 2 3 4]b=[1 3 5 9]
c=a./b
Element-wiseop.Element-wisesquare
D.^2
Vectorandconstant
visvector,cisscalar
v=[1234]c=2
Vectorandconstant
Whenconstantisadded/substracted tothevector, itisadded / substracted fromEACHelement
v-cv+c
Vectorandconstant
Constantcansimplymultiplyordivideavector
v/cv*c
Vectorandconstant
Howeveronlyc./v isdefinedandgives[c/v(1)...c/v(length(v))
c./v
Matrixandvector
Forthispurposes,wedefineavectoras2Dmatrixwithonedimensionequalto1.
x=[123]'%remember' meanstranspose
Matrixandvector
Multiplication
x=[123]'A=[1-23;012;001]
b=A*x
Matrixandvector
Matrixinversionorhowtosolvelinearsystem
x_solved=inv(A)*b :equationAx=b; solvedx=inv(A)b
Matrixandvector
Solvingasystemoflinearequations inanotherway
x_solved_another_way=A\b (\ : backslash)
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!
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
Part4.Matrixfunctions
• Squarerootsofelementsofamatrix• Aggregatefunctions• Specialmatrices• Transformmatrices•Multidimensionalarrays• Structures
Squareroots
Squarerootsofeachelementsofamatrix
F=[149;162536]
F_= sqrt(F)
Aggregate:Sum
Aggregateelementsbysummingoperation
A=[1234;5678;9101112]
Aggregate:Sum
Summationperformedbyfirst index(sumsofcolumns)
A=[1234;5678;9101112]
sum(A)
Aggregate:Sum
Summationperformedbysecondindex(sumsofrows)
A=[1234;5678;9101112]
sum(A, 2)
Aggregate:Sum
Sumofthewholematrix
A=[1234;5678;9101112]
sum(sum(A))
Aggregate:Product
Productperformedbyfirst index(productofcolumns)
A=[1234;5678;9101112]
prod(A)
Aggregate:Product
Productperformedbysecondindex(productofrows)
A=[1234;5678;9101112]
product(A, 2)
Aggregate:Product
Productofthewholematrix
A=[1234;5678;9101112]
product(product(A))
Aggregate:MeansandStandardDeviations
Meanbyfirst index(meanofcolumns)
mean_A_column=mean(A)
Aggregate:MeansandStandardDeviations
Meanbysecondindex(meanofrows)
mean_A_row=mean(A,2)
Aggregate:MeansandStandardDeviations
Standarddeviationbyfirst index(s.d. ofcolumns)
std_A_column=std(A)
Aggregate:MeansandStandardDeviations
Standarddeviationbysecondindex(s.d. ofrows)
std_A_row=std(A,[],2)
[]MUSTbehere
Specialmatrices
Diagonalmatrix
diagonal_matrix=diag([1234])
Specialmatrices
Zeromatrix
all_zeros=zeros(3,4)
Specialmatrices
Onematrix
all_ones=ones(4,2)
Specialmatrices
Unitmatrix
unit_matrix=eye(4)
Transformofmatrix
Matrix(array)repetition
v=[123];
V1=repmat(v,3,1)
Numberofrowrepetition
Numberofcolrepetition
Transformofmatrix
Matrix(array)repetition
v=[123];
V2=repmat(v,1,3)
Numberofrowrepetition
Numberofcolrepetition
Transformofmatrix
Matrix(array)repetition
v_tran=v';vv_tran=repmat(v_tran,3,1)
Transformofmatrix
Matrix(array)reshape
A=[123456789101112];
A_matrix=reshape(A,3,4)
3*4=length(A),i.e.totalnumberofelementsmustnotchange
Transformofmatrix
Multidimensionalarrays
MX=zeros(3,3,3)
Transformofmatrix
Multidimensionalarrays
A=[123456789101112];
MX=reshape(A,2,3,2)
2*3*2=length(A),i.e.totalnumberofelementsmustnotchange
StructuresStructureisanobjectwithaccessibleattributesbyitsname
weather=struct('temp',72,'rainfall',0.0)
weather.temp
Structures
Initialize3rd elementofweatherarray
weather(3)=struct('temp',72,'rainfall',0.0)
Structures
createsweathermatrixwiththesameinitialvalues
weather=repmat(struct('temp',72,'rainfall',0.0),1,3)
CellStructures
Cellcancontainmultipleelementswithdifferenttypes
A ={[143;058;729], 'AnneSmith'; 3+7i, -pi:pi/4:pi}
CellStructures
A(1):accesscellelement
A{1}:returnscontents acellelement
Part5.Specialtopics
• Howtoplotresults• Findfunction• Sortfunction• Randomnumbergeneratorsandhistograms• Randommatrices
PlotResults
Preparedata
A=[1234579];B=[1213141411108];
PlotResults
Plottwovectorsinsamelength
plot(A,B);
PlotResults
Retainpreviousfigureandaddnewgraphonit
C=B-4;Holdon;plot(A,C,'*-r')
Newlinewithreadcolorandhasstarsandlines
Retainoldgraph
PlotResults
Addlabel,title,andlegend
xlabel('Month')ylabel('Powerconsumption')title('Thisisdemograph')legend('NewYork','Pittsburgh')
PlotResults
Createnewplot(holdoff)
holdoff;plot(A,C./B);title('Consumptionratio')
PlotResults
Opennewplot(figure;)
figure;C=eye(10,10);imagesc(C);title('Thewaytoplotmatrices')
imagesc:displayimage(matrix)withscaledcolors
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
PlotResults
2Dplotofthesamefunction
imagesc(Z);colorbar
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
Find
Pickscomponentssatisfyingacondition
a=[12345];
find(a>2)
Outputsareindicesthatcorrespondtovaluesofvectorthatsatisfythepredicate(a>2)
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
Sortfunction
Let’ssaywehavestudentsidsandcorrespondingscores
scores=[9455231210];students=[102232343242343451223232];
Sortfunction
Studentpointssortedaccordingtotheresultsontest
[scores,index]=sort(scores);
Sortfunction
Reorderstudentidsbytheindexfromsortfunction
B=B(index)
Sortfunction
Let’ssortrowsorcolumnsofmatrices
A=[123; 1098; 567]
Sortfunction
Eachcolumnisindependentlysorted
sort(A,1)
Sortfunction
Eachrowisindependentlysorted
sort(A,2)
Randomnumbergenerator
RandomvectorsfromNormal(Gaussian)distribution
normal_vector=randn(1000,1);
Numberofrow
Numberofcol
Randomnumbergenerator
Createhistogramofrandomnumbers
normal_vector=randn(1000,1);hist(normal_vector,20)title('Normaldistribution')
20:numberofbinsinhistogram
Randomnumbergenerator
RandomvectorsfromUniformdistribution
uniform_vector=rand(1000,1);
Numberofrow
Numberofcol
Randomnumbergenerator
Createhistogramofrandomnumbers
uniform_vector=rand(1000,1);hist(uniform_vector,20)title('Uniformdistribution')
20:numberofbinsinhistogram
Randomnumbergenerator
Createhistogramofrandomnumbers
uniform_vector=rand(1000,1);hist(uniform_vector,20)title('Uniformdistribution')
20:numberofbinsinhistogram
Randomnumbergenerator
Histogramofrandomvectorfromchi-squaredistribution
chi_square_vector_df3=chi2rnd(3,1000,1)hist(chi_square_vector_df3,20)title('\chi^{2}distribution')
20:numberofbinsinhistogram
Generaterandompermutation
fori=1:3A=randperm(10)
end
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)
Thanks!-
Questions?