Sei sulla pagina 1di 25

The image cannot be display ed.

Your computer may not hav e enough memory to open the image, or the image may hav e been corrupted. Restart y our computer, and then open the file again. If the red x still appears, y ou may hav e to delete the image and then insert it again.

BASICS OF MATLAB

Introduction
MatLab :MatrixLaboratory Dr.CleveMolder
MATLABisaninterpretedlanguagenocompilationneeded(but
possible)
NumericalComputationswithmatrices
WhyMatLab?
UserFriendly(GUI)
Easytoworkwith
Powerfultoolsforcomplexmathematics

MatLab hasextensivedemoandtutorialstolearnbyyourself
Usehelpcommand

Features

Donthavetodeclaretype
Dontevenhavetoinitialise
Dynamicmemoryallocation
Basiccomputationunitisamatrix
Indexingstartsfrom1insteadof0
Greatvisualisationcapabilities
Loadsofbuiltinfunctions
Easytolearnandsimpletouse

TheMATLABInterfaces

Workspace

Command Window

Command History
4

CreatingVariables
Itcanbeanystringofupperandlowercaselettersal
ongwithnumbersandunderscoresbutitmustbegi
nwithaletter
ReservednamesareIF,WHILE,ELSE,END,SUM,e
int a;
tc.
double b;
Namesarecasesensitive
float c;
Thevariablesare1x1matriceswithdoubleprecision
No need for types. i.e.,
[Datatypes..]

>>a=12;%variableaisassigned12

Example:
>>x=5;
>>x1=2;

SingleValues
Singletons
Toassignavaluetoavariableusetheequals
ymbol=
>>A=32

Tofindoutthevalueofavariablesimplytype
thenamein
Thevalueoftwovariablescanbeaddedtoget
her,andtheresultdisplayed
>>A=10
>>A+A

ortheresultcanbestoredinanother
variable
>>A=10
>>B=A+A

NumericTypes

Numeric classes includes signed and unsigned integers, and single-precis


ion and double-precision floating-point numbers
By default MATLAB stores all numeric values as double-precision floating
point

Vectors

Avectorisalistofnumbers
Usesquarebrackets[]tocontainthenumbers
Tocreatearowvectoruse,toseparatethecontent

Tocreateacolumnvectoruse;toseparatethecontent

Vectors

Arowvectorcanbeconvertedintoacolumnvectorbyusingthe
transposeoperator
Try this ??

o
o
o
o
o
o

Max(),min();
max/minelementofavector
Std(),var(); standarddeviationandvariance
Sum(),prod();
sum/productofelements
Sort();
sortinascendingorder
Mean(),median();
linspace(a,b,n);

The:operator
VERYimportantoperatorinMatlab
Meansto
Try the following
>> x=0:pi/12:2*pi;
>> y=sin(x)

>>1:10
ans=
12345678910
>>1:2:10
ans=
13579
10

Matrices

Dontneedtoinitialisetype,ordimensions

square brackets to define matrices

>>A=[321;510;217]
A=
321
510
217
>>
semicolon for next row in matrix

Listthenumbersusing,toseparateeachcolumnand
then;todefineanewrow
11

MatrixIndex

Thematrixindicesbeginfrom1(not0
(asinC))
Thematrixindicesmustbepositiveinteger

Given:

A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers or logicals.
A(4,2)
Error: ??? Index exceeds matrix dimensions.

>> A(:)

>> A(:,2:3)

ans =

ans =

3
6
2
5
8
7
3
2
3

5
8
7

3
2
3

ChangingMatrixRowsorColumns

>>

To change all of the values in a row or column to zero


use
results(:, 3) = 0

Try this ??

>> results(:, 5) = results(:, 3) + results(:, 4)

>> results(3, :) = [10, 1, 1, 1]


>> results(:, 3) = [1; 1; 1; 1; 1; 1; 1]
13

ManipulatingMatrices
>>A' %transpose
>>B*A %matrixmultiplication
>>B.*A%elementbyelementmultiplication
>>B/A %matrixdivision
>>B./A
%elementbyelementdivision
>>[BA]
%Joinmatrices(horizontally)
>>[B;A]
%Joinmatrices(vertically)
Enter matrix
B into the
Matlab
workspace

A=
3
5
2

2
1
1

1
0
7

B=
1
4
2

3
9
7

1
5
2

Create matrices A and B and try out the the matrix operators
in this slide
14

MatricesOperations
Try this ??

Given A and B:

>> ones(rows, columns)


>> rand(rows, columns)
>> zeros(rows, columns)
>> eye(m, n)
>> magic(m)

Addition

Subtraction

Product

Transpose

Theuseof. ElementOperation
A = [1 2
A=
1
5
3

3; 5 1 4; 3 2 1]
2
1
2

3
4
-1

x = A(1,:)

y = A(3 ,:)

b = x .* y

c=x./y

d = x .^2

x=

y=

b=

c=
0.33
3

d=

3 4 -1

3 8-

0.5

K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.

ConcatenationofMatrices

x=[12],y=[45],z=[00]
A=[xy]%HorizontalConcatenation
1245
B=[x;y]%Verticalconcatenation
12
45
C = [x y ;z]

Error:
??? Error using ==> vertcat CAT arguments dimensions are not
consistent.

BasicMatrixFunctions
Inv (A);

% inverse of A

sum(A);

%summation.

Rank(A);

% rank of matrix A

%transpose of A

Det (A)

%determinant

dot(a,b)

%dot product of two vectors

Cross(a,b)

%cross product of two vectors

V= eig (A)

% eigenvalue vector of A

Size(A):

% return [m n]

Length(A):

% length of a vector

max(size(A));

Try this ??

Creating Matrices

zeros(m, n) : matrix with all zeros


ones(m, n) : matrix with all ones.
eye(m, n) : the identity matrix
rand(m, n) : uniformly distributed random
randn(m, n) : normally distributed random
magic(m) : square matrix whose elements
have the same sum, along the
row, column and diagonal.
pascal(m) : Pascal matrix.

B = A(2:4,3:5); % B is the subset of A


A(:, 2)=[];

% Delete second column


18

Operators(relational,logical)

==Equalto
~=Notequalto
<Strictlysmaller
>Strictlygreater
<=Smallerthanorequalto
>=Greaterthanequalto
&Andoperator
|Oroperator

ScriptsandFunctions
There are two kinds of Mfiles:
Scripts, which do not accept input arguments or return ou
tput arguments. They operate on data in the workspace.
Functions, which can accept input arguments and return
output arguments. Internal variables are local to the funct
ion.

FlowControl
if
for
while
break

ControlStructures
IfStatementSyntax
if(Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end

Some Dummy Examples


if ((a>3) & (b==5))
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end

Control Structures
Forloopsyntax

Some Dummy Examples


for i=1:100
Some Matlab Commands;
end

fori=Index_Array
Matlab Commands
end

for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end

ControlStructures

WhileLoopSyntax

while(condition)
Matlab Commands
end

Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end

VisualizationandGraphics

plot(x,y),plot(x,sin(x)) plot1Dfunction
figure,figure(k) openanewfigure
holdon,holdoff refreshing
mesh(x_ax,y_ax,z_mat) viewsurface
contour(z_mat) viewzastop.map
subplot(3,1,2) locateseveralplotsinfigure
axis([xmin xmax ymin ymax]) changeaxes
title(figuretitle) addtitletofigure

Potrebbero piacerti anche