Vous êtes sur la page 1sur 22

1

Matlab Matrices
Matlab treats all variables as matrices.
Vectors are special forms of matrices and contain only one row OR one
column.
Scalars are matrices with only one row AND one column

Row Vector
Example :
>> a = [1, 2 , 3]
a=
1 2 3

Column Vector
gives

Example :
>> a = [1; 2; 3]
a=
1
2
3

gives

Matrix
a = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
a=
1 2 3
4 5 6
7 8 9
3

Extracting a sub matrix


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.

Column and Row extraction


Here we extract column 2 of the matrix and
make a column vector:
col_two=matrix( : , 2)
2
5
8

Here we extract row 2 of the


matrix and make a row vector:
row_two=matrix( 2 , :)
4 5 6

Assignment & Operators


Assignment
Addition
Subtraction
Multiplication
Division
Power

=
+
* or.*
/ or ./
^ or .^

a = b (assign b to a)
a+b
a -b
a*b or a.*b
a/b or a./b
a^b or a.^b

Differences b/w Multiplication and Dot Multiplication


A*A is matrix multiplication.
A.*A is element-by-element multiplication.

Matlab Matrices
Accessing Single Elements of a Matrix
A(i,j)
Accessing Multiple Elements of a Matrix
A(1,4) + A(2,4) + A(3,4) + A(4,4)
Deleting Rows and Columns
To delete the second column of X, use X(:,2) = []
Concatenating
C=[A;B]

Some Matlab(matrix) functions


X = ones(r,c)
X = zeros(r,c)
A = diag(x)
[r,c] = size(A)
v = sum(A)
X = A
X = inv(A)
X = pinv(A)

% Creates matrix full with ones


% Creates matrix full with zeros
% Creates squared matrix with vector x in diagonal
% Return dimensions of matrix A
% Vector with sum of columns
% Transposed matrix
% Inverse matrix squared matrix
% Pseudo inverse

Expressions: Matlab Logical Functions


any (x)
all (x)
isnan (x)
isinf (x)
finite (x)

returns 1 if any element of x is nonzero


returns 1 if all elements of x are nonzero
returns 1 at each NaN in x
returns 1 at each infinity in x
returns 1 at each finite value in x

Other Matrix Operations


eye(a,b)
rand(a,b)
randn(a,b)
Pascal(a)
Magic(a)

- creates an identity matrix


- matrix with uniformly distributed random values
- matrix with normally distributed random values
- generates a pascal square matrix
- generates a magic matrix

fliplr(X) -- returns X with row preserved and columns flipped in the left/right direction.
flipud(X) -- returns X with columns preserved and rows flipped in the up/down direction.
flipdim(X,Dim) -- Flip matrix along specified dimension
rot90() -- is the 90 degree counter clockwise rotation of matrix A.
tril
-- the lower triangular part of X
triu
-- the upper triangular part of X.

Linspace Function
Generates a vector of evenly spaced points between two end points,
linspace(start,stop,npoints ):
x = linspace(0,1,10)
x=
Columns 1 through 7
0 0.1111 0.2222 0.3333 0.4444 0.5556 0.6667
Columns 8 through 10
0.7778 0.8889 1.0000

Repmat function
The repmat function can be used to replicate a matrix:
a = [1 2; 3 4]
repmat(a,2,3)
ans =
1 2 1 2 1 2
3 4 3 4 3 4
1 2 1 2 1 2
3 4 3 4 3 4
10

Basic Data Analysis Functions


max
min
find
mean
median
std
sort
sortrows
sum
Prod
diff
trapz
cumsum
cumprod
cumtrapz

maximum
minimum
find indices of nonzero elements
average or mean
median
standard deviation
sort in ascending order
sort rows in ascending order
sum of elements
product of elements
difference between elements
trapezoidal integration
cumulative sum
cumulative product
cumulative trapez integration
11

Find function
I = FIND(X) returns the linear indices corresponding to the nonzero entries of the array X. X
may be a logical expression.
I = FIND(X,K) returns at most the first K indices corresponding to the nonzero entries of the
array X. K must be a positive integer, but can be of any numeric type.

round(X) -- rounds X to the nearest integer.


ceil(X)

-- rounds X to the nearest integer towards

floor(X) -- rounds X to the nearest integer towards -


fix(X)

-- rounds X to the nearest integer towards 0

12

Some important Trigonometric functions


sin(x)
cos(x)
tan(x)
asin(x)
acos(x)
atan(x)

13

Loading and Saving Data


save filename varaibles
save test.mat x y
load filename
load test.mat

Explanation of editor window..............

14

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
~=
MATLAB supports three logical operators.
not ~
% highest precedence
and &
% equal precedence with or
or
|
% equal precedence with and

15

Matlab Branching
if condition
statements A
else
statement B
end

If else

NOTE: Dont forget end, or MATLAB will wait forever.

If elseif-else

if condition1
statement A
elseif condition2
statement B
elseif condition3
statement C
...
else
statement E
end
16

Matlab Branching (contd.)


if condition1
statement A
if condition2
statement B
end
end

Nested ifs

for loop
for index = j:k {for index = j:m:k}
statements
end

for loop - break


for

index = j:m:k
statements

if condition
break
end
end
17

Matlab Branching (contd.)


while expression
commands
..
..
if condition
break
end
end

while loop - break

18

Function format
function variables = function_name(variables)
commands
Commands
Example :
function s = generatesin(fs,f,t)
commands
s1 = generatesin(8000,2,2)
s2 = generatesin(8000,100,0.2)

19

Matlab Graphics
plot(y) - In this case the elements of y are plotted against their indexes
HOLD ON holds the current plot and all axis properties so that subsequent graphing
commands add to the existing graph.
SUBPLOT(m,n,p)
Breaks the Figure window into an m-by-n matrix of small axes, selects the p-th axes for the
current plot.
Example :
subplot(2,1,1), plot(x);
subplot(2,1,2), plot(y);

Useful Graphical Functions


xlabel
-- Labeling the x-axis
ylabel
-- Labeling the y-axis
title
-- Title of the plot
grid
-- Enables or Disables the grid of the plot
axis( [xmin, xmax, ymin, ymax] ) - To limit the plot in the corresponding asix
linkaxes(ax,'x')

To save a figure
saveas(gcf,wavFile,'eps')

20

Different Graphical Representations


bar() -- Represents the graph as vertical bars
hist() -- bins the elements of Y into equally spaced containers and returns the no.
of elements in each container.
mesh() - plots the colored parametric mesh defined by the arguments with in the
function.
zplane(Z,P) -- plots the zeros Z and poles P (in column vectors) with the unit
circle for reference. Each zero is represented with a 'o' and each pole with a 'x'
on the plot.
More functions : surf, stairs, ribbon, compass etc

21

Example: Audio signals


Reading the .wav file: [s,fs]=wavread(wavFile_name);
Writing the .wav file: wavwrite(y,fs,wav_name)
Listening to the file: soundsc(s,fs)
Recording the wav file: s = wavrecord(T,fs,data_type)

Example: Images
Reading the image: s=imread('Lena256.bmp');
Converting the bitmap: im2double(s);
Converting to a displayable structure: mat2gray(S)
Displaying the image: imshow(r3)
Color to gray conversion: rgb2gray(s)
Writing the images: imwrite(s,filename,format)

22

Vous aimerez peut-être aussi