Sunteți pe pagina 1din 32

Getting started with

Matlab

Topics:
- User Interface
- Simple calculations
- Matrices/Vectors
- Functions
- Loops/conditions
- Plots
User Interface
Simple Calculations

UsingMatlabascalculator:
>>5*2 (MatlabusestheVariableanstostorethe
ans= resultofanunassignedcalculation)
10

>>(2+3)*5; (Asemicolonattheendofthecommandsuppressestheoutput.
Interally,thevariableansissetto25.)

DefiningVariables:
>>a=3;
>>b=5;
>>c=a+b; (c=8)

Variablesareavailableduringyourentiresessionandappearintheworkspace
Theworkspacecanbeclearedwiththecommand >>clear
Matlabhassomepredefinedconstants,e.g.pi
Simple Calculations

Thewayinwhichnumbersappear
Thefunctionformatcontrolsthenumericformatofthedispayedvalues.The
functionaffectsonlyhownumbersaredisplayed,nothowMATLABcomputesor
savesthem.

>>formatshort; 5digits(thedefault)

>>formatlong; 15digits

>>formatrat; trytorepresenttheanswerasarationalnumber

Examplesforpi:
short: 3.1416;
long: 3.14159265358979;
rat: 355/133;
Simple Calculations

MathematicalFunctions:
Arithmetic functions: +,,*,/
Exponential functions: ^,exp,log,log10

Trigonomertic functions: sin,cos,tan,asin,acos,atan

Other functions: round,mod,abs,sign...

Examples:
>>4*x^5; (= 4x 5 )

>>exp(3)*sin(x); (= e 3sin x )

>>mod(12,5); (= 2 )
Simple Calculations

Exercise
Calculate the following expressions:

a
b
ba
b
ca
(fora=1,b=5,c=2)

2cos
loge
Simple Calculations

Exercise
Calculate the following expressions: Solutions:

a >>a=1;
b >>b=5;
ba >>c=2;
b >>ba/(b+(b+a)/(c*a))
ca
(fora=1,b=5,c=2) ans=

4.500

2cos
loge >>log(exp(2+cos(pi)))

ans=

1
Vectors / Matrices in Matlab

MatricesarethebasicdataelementofMatlab(MATLAB=MATrixLABoratory)

EnteringMatrices:
Separatetheelementsofarowwithblanksorcommas.
Useasemicolontoindicatetheendofeachrow.

Surroundtheentirelistofelementswithsquarebrakets[]

Example:
>>A=[324;120;243]

A=

324
120
243
Vectors / Matrices in Matlab

Rowvectorsare1xnmatricesandcolumnvectorsarenx1matrices.

rowvector >>a=[412] columnvector: >>b=[4;1;2]


a= b=
412 4
1
2
CreatingMatricesfromvectors:
column >>a=[4;1;2]; row >>a=[412];
>>b=[2;3;3]; >>b=[233];
vectors: vectors:
>>c=[1;2;0]; >>c=[120];

>>C=[abc] >>D=[a;b;c]

C= D=
421 412
132 233
230 120

Concatenationofmatrices:

E=[CD;DC]; Note: Dimensions must be consistent!


Vectors / Matrices in Matlab

Sinceeverythingisamatrixinmatlab,allscalaroperationscanalsobe
appliedtovectors/Matrices(aslongsasthedimensionsareconsistent)
Examples:
>>A+4; Scalaropreationsareappliedcomponentwise
>>sin(A);
>>mod(A,2); andamatrixofsamedimensionisreturned.
>>mod(A,B);

OperationswhicharewelldefinedformatricesareNOTapplied
componentwise
Example:MatrixMultiplication

>>A=[123;210;121];>>B=[121;121;121]

>>A*B componentwise: >>A.*B

ans=6126 ans=143
363 220
484 141
Vectors / Matrices in Matlab

Variousfunctionsonmatrices:

A' Transposeoperator
size(A) #ofrowsandcolums(returnedinarowvectorofdimension2)
diag(A) diagonalofasquarematrix(returnedinacolumnvector)
det(A) Determinant
inv(A) MatrixInversion
lu(A) LUDecompostionof
...

Generatingmatrices:

zeros(m,n) nxmmatrixwithallzeros
ones(m,n) nxmmatrixwithallones
eye(m) mxmidentitymatrix
rand(m,n) nxmmatrixwithrandomvalues
magic(m) mxmmagicmatrix
Vectors / Matrices in Matlab

Accessingsinglematrixelements:
A(i,j) ElementinrowiandcolumnjoftheMatrixA
A(i) Usuallyusedtogettheithcomponentofavector

Accessingmultiplematrixelements:
A(:,j) jthcolumnvectoroftheMatrixA
A(i,:) ithrowvectoroftheMatrixA
A(1:3,j) first3elementsofjthcolumnvectoroftheMatrixA

Additional Notes:
theseoperationscanbeusedreadANDtomanipulatedata.
>>c=A(1,2);storetheelementA12inthevariablec
>>A(1,2)=3;setA12tothevalue3
>>A(:,2)=[];deletethesecondcolumnofA

Youcanusethekeywordendtoaccessthelastentry:
>>A(end,2);lastentryofthesecondcolumnvector
Vectors / Matrices in Matlab

Exercise 1 1 3 2
2 4 7 0
Prerequisite:DefinetheMatrix A=
1 0 2 5
8 3 1 2

Tasks:
Extracttheupperleft3x3submatrixofA

Computethedotproductofthemain
diagonalofAandthefourthcolumnvector
ofA.

DefineaMatrixBwhicharisesfrom
interchangingthe1standthe4throwofA

Settheentire3rdcolumnofAto'1'

Inserttherowvector(1234)atthebottom
ofA:
Vectors / Matrices in Matlab

Exercise 1 1 3 2
2 4 7 0
Prerequisite:DefinetheMatrix A=
1 0 2 5
8 3 1 2

Tasks: Solutions:
Extracttheupperleft3x3submatrixofA >>A(1:3,1:3)

Computethedotproductofthemain >>diag(A)'*A(:,4)
diagonalofAandthefourthcolumnvector
ofA.

DefineaMatrixBwhicharisesfrom >>B=[A(4,:);A(2:3,:);A(1,:)]
interchangingthe1standthe4throwofA

>>A(:,3)=1;
Settheentire3rdcolumnofAto'1'

Inserttherowvector(1234)atthebottom >>A(end+1,:)=[1234];
ofA:
Writing Functions in Matlab

AselfdefinedFunctionisstored
inafile:<functionName>.m

All.mfilesinthecurrent
directoryareavailableinyour
commandwindow
Writing Functions in Matlab

Skeletonofafunction:
function[output_args]=<functionName>(input_args)
%FUNCSummaryofthisfunctiongoeshere
%Detailedexplanationgoeshere

Example:
Functionwhichreturnsthesumofthetopleftandthebottomrightelementofamatrix:

nonsense.m

function[r]=nonsense(A)

r=A(1,1)+A(end,end);

end

Note:Neitherthetype,northedimensionsoftheparametershastobespecified
Writing Functions in Matlab

FunctionswithmorethanoneParameter:
GetthetwodifferentProductsoftwoMatricesinonefunctioncall:

function[ABBA]=MatrixMult(A,B)

AB=A*B;
BA=B*A;

end

>>A=[123;234;102];
>>B=[012;241;531];
>>[M1,M2]=MatrixMult(A,B);


9125 8114
M1=6147 M2=13204
182512 14237
Writing Functions in Matlab

Exercise:
Writeafunctionld(x)whichreturnsthelogarithmofanumberxtothebasis2.
Writing Functions in Matlab

Exercise:
Writeafunctionld(x)whichreturnsthelogarithmofanumberxtothebasis2.

Solution:

function[r]=ld(x)
r=log(x)/log(2);
end
Loops / Conditions

Loops
fori=N repeatsthecommandsforeachelementofavectorN.
... Thecurrentlyprocessedvectorelementisavailable
commands
insidetheloopviatherunningparameter(here:i)
...
end

Avectorwithincrementalelementscaneasilybecreatedwiththe
colon(:)operator

>>t=1:10 defaultincrementis1

t=12345678910

>>s=2:0.2:3 explicitlysettingthedefault

s=2.02.22.42.62.83.0
Loops / Conditions

Conditions

if(expression)
... Iftheexpressionistrue,thecommandsare
commands executed,otherwisetheprogramcontinueswiththe
... nextcommandimmediatelybeyondtheend
end statement

Youcancreatealternativecommandsectionswithelseandelseif:

if(expression1) assoonasoneoftheexpressionsistrue,the
...
elseif(expression2) respectivecommandsareexecutedandthe
... programcontinuesbeyondtheendstatement.
elseif(expression3)
... Thecommandafteranelsestatementare
else
... executedwhennoneoftheconditionsaretrue.
end
Loops / Conditions

Conditions

Examplesforexpressions:
(a<b) Trueifaislessthanb
(a==b) Trueifaisequaltob
(a~=b) Trueifaisnotequaltob

Compoundstatements:

(x<3&y<4) LogicalAND
(x<3|y<4) LogicalOR
Loops / Conditions

n
Exercise: Writeafunctionfact_or_sum(n)whichcomputes i if
nisevenandn!ifnisodd(forn>0) i=1
Loops / Conditions
n
Exercise: Writeafunctionfact_or_sum(n)whichcomputes i if
i =1
nisevenandn!ifnisodd(forn>0)

Solution: function[res]=fact_or_sum(n)

res=1;
fori=2:n
if(mod(n,2)==1)
res=res*i;
else
res=res+i;
end
end
end
Loops / Conditions

ConditionalLoops

while(condition)
The loop is repeated as long as the condition is
...
satisfied
commands
...
end

Thebreakcommand
breakcanbeusedtoforceanylooptoend;

x=1;
while(1==1)
x=x+1;
ifx>10
break
end
...
end
Plots

Theplotfunctionhasdifferentforms,dependingontheinputarguments.

Ifyisavector,plot(y)producesapiecewiselineargraphofthe
elementsofyversustheindexoftheelements

>>y=[312524];

>>plot(y)

Note:Graphingfunctionsautomaticallyopenanewfigurewindowif
therearenofigurewindowsalreadyonthescreen.Ifafigurewindow
exists,itisusedforgraphicsoutput.
Plots

Ifyouspecifytwovectorsasarguments,plot(x,y)producesagraph
ofyversusx.

>>x=[0:2:10];
>>y=[1244.530];

>>plot(x,y)

x 0 2 4 6 8 10
y 1 3 4 4.5 3 0
Plots

Specifyinglinestyles,colorsandmarkers

plot(x,y,'color_style_marker')

color_style_markerisastringcontainingfromonetofourcharacters
(enclosedinsinglequotationmarks)constructedfromacolor,alinestyle,and
amarkertype.Thestringsarecomposedofcombinationsofthefollowing
elements:

Color: Line Style: Marker Type:


'c' cyan '' solid '+' plusmark
'm' magenta '' dashed 'o' unfilledcircle
'y' yellow
':' dotted
'*' asterisk
'r' red 'x' letterx
'.' dashdot
'g' green 's' filledsquare
noline
'b' blue nomarker
'w' white ...
'k' black
Plots

Examples:

>>plot(x,y,'ks')

plots black squares at each data point, but does not connect the markers
with a line.

>>plot(x,y,'r:+')

plots a red-dotted line and places plus signs at each data point
Plots

Plottingmultipledatasetsinonegraph
Multiple x-y pairs as arguments create multiple graphs with a single call to plot

>>plot(x,y,x,y2,x,y3)

Addingplotstoanexistinggraph
if you type the command holdonMATLAB does not replace the existing graph
when you issue another plotting command; it adds the new data to the current
graph, rescaling the axes if necessary.

>>plot(x,y);
>>holdon
>>plot(x2,y2);
>>holdoff
Plots

Exercise
Create a plot of sin(x) with 100 data points in the interval [0,2 ]
Plots

Exercise
Create a plot of sin(x) with 100 data points in the interval [0,2 ]

Solution:
>>s=2*pi/99;

>>x=0:s:2*pi;

>>y=sin(x);

>>plot(x,y,'r:+')

S-ar putea să vă placă și