You are on page 1of 8

De La Salle University

Electronics and Communications Engineering Department


Matlab Fundamentals
Laboratory Experiment 1
I. Objectives :
[1.] To be able to familiarize with some of the commands and capabilities of MATLAB.
[2.] To be able to learn how to do Matrix/Vector manipulation, complex algebra, and graphics in MATLAB
II. Introduction
Matlab is a technical computing environment for high-performance numeric computation and
visualization. Matlab integrates numerical analysis, matrix computation, signal processing, and graphics in
an easy-to-use environment where problems and solutions are expressed just as they are written
mathematically-without traditional programming.
Matlab can be started by entering matlab at the system prompt or by clicking on the MATLAB
icon, depending on the machine you are using. Once invoked, MATLAB will clear the screen, provide some
introductory remarks, and produce the MATLAB prompt >>. To quit MATLAB, type quit or exit followed
by carriage return key.
2.1 Fundamental expressions
Working with the MATLAB environment is straightforward because most commands are entered
as you write them mathematically.
2.1.1 Variable

Expression typed without a variable name are evaluated by MATLAB and the result is stored and
displayed by a variable called ans. The result of an expression can be assigned to a variable name. Variable
names can have as many as 19 characters (including letters and numbers). However, the first character must
be a letter. Matlab is case sensitive. The command casesen makes MATLAB insensitive to the case. For
example, entering the following expression
>> x=exp(-0.2696*.2)*sin(2*pi*0.2)/(0.01*sqrt(3)*log(18))
The result is displayed on the screen as
x=
18.0001
If you do not care to create a new variable but want to know the value of an expression, you can
type the expression by itself, e.g.,
>>4/3
which yields
ans =
1.3333

SIGSLAB

Laboratory Experiment 1

Page 1-1

If you wish to create a new variable but do not want to see the MATLAB response, type a
semicolon at the end of the expression. For example,
>>a = 4 + 3;
It will create a new variable a whose value is 11, but MATLAB will not display the value of a. The
semicolon is very useful when large vectors or matrices are defined or computed in intermediate step of a
computation. You can check the value of variable at any time by entering the variable name at the prompt.
For example,
>> a
a=
7
MATLAB has several predefined variables. These are given in table 1.1
Table 1.1 Special Variables and Constant
ans
Most recent answer
computer
Computer Type
eps
Floating point relative accuracy
flops
Count of floating point operations
i,j
Imaginary unit
inf
Infinity
NaN
Not-a-Number
nargin
Number of function input arguments
nargout
Number of function output arguments
pi
3.1415926535897...
realmax
Largest floating point number
realmin
Smallest floating point number
Notice that MATLAB display the result with 5 significant digits (default format: format short). The
commands format short e, format long, and format long e display 5 digits floating point, 15 digits fixed
point, and 15 digits floating point, respectively. For more flexibility in the output format, the command
fprintf displays the result with a desired format on the screen or to specified filename. For example, the
command
>>fprintf(Area = %7.3f Square meters \n,pi*4.5^2)
result in
Area = 63.617 Square meters
The %7.3f prints a floating point number at least 7 characters wide, with 3 digits after the decimal
point . The sequence \n advances the output to the left margin on the next line
2.1.2 Character String
A sequence of characters in single quotes is called a character string or text variable.
>> c = Good
result in

SIGSLAB

Laboratory Experiment 1

Page 1-2

c=
Good
A text variable can be augmented with more text variable, for example,
>>cs = [ c, luck]
produces
cs =
Goodluck
2.2 Elementary Matrix Operation

Matrices are entered into MATLAB by listing the elements of the matrix and enclosing them
within a pair of brackets. Elements of a single row are separated by commas or blanks, and rows are
separated by semicolons or carriage return. For example,
>> A = [1 2; 3 4]
yields the MATLAB response
A=
1
3

2
4

and
>> A = [1, 2
3, 4]
produces the same result.
The entire row or column of a matrix can be addressed by means of the symbol (: ). For example,
>> a3 = A(2 , : )
results in
r3 =
3 4
Similarly, the statement A( : , 2) addresses all elements of the second column in A. Typing A( : ) will return
all the elements of A.
Matrices of the same dimension can be added or subtracted. Two matrices, A and B, can be
multiplied together to form the product AB if they are comformable. A \ B is equivalent to A-1 B, and A/B is
equivalent to A B-1. The inverse of a matrix can be obtained using the MATLAB function inv
MATLAB has commands for generating special matrices. For example, you can create a diagonal
matrix with the diag command using a vector containing the diagonal elements as the input argument, such
as
>> D = diag ( [1 2] )

SIGSLAB

Laboratory Experiment 1

Page 1-3

Other special matrices that can be generated are given in table 1-2.
Table 1-2. Elementary Matrices
eye
Identity Matrix
meshgrid
X and Y arrays for 3-D plots
ones
Ones matrix
zeros
Zeros matrix
rand
Uniformly distributed random numbers
randn
Normally distributed random numbers
Matrices can be manipulated using the following MATLAB functions (see Table 1-3).
Table 1 -3 Matrix Manipulation
diag
Create or extract diagonal
fliplr
Flip matrix in the left/right direction
flipud
Flip matrix in the up/down direction
reshape
change size
rot90
Rotate matrix 90 degrees
tril
Extract lower triangular part
triu
Extract upper triangular part
:
Index into matrix, rearrange matrix
Table 1 -4 shows some of the Matrix function available in Matlab
det
Determinant
norm
Matrix or vector norm
trace
Sum of diagonal elements
inv
Matrix inverse
eig
Eigenvalues and eigenvectors
poly
characteristic polynomial
expm
Matrix exponential
logm
Matrix logarithm
sqrtm
Matrix square root

2.3 Vector Operation


An n vector is a row vector or a column array of n numbers. In Matlab, elements enclosed by
brackets and separated by semicolon generate a column vector.
The transpose of a row vector is a column vector, and vice versa. This can be done in Matlab using
the symbol ( ). For example,
>> Y=R
means Y is the transpose of a vector or matrix R.
Vectors of the same size can be added or subtracted. The operation ( .* ) performs element-byelement multiplication.
The ( : ) can also be used to generate a row vector. For example,
>>x = 1:8

SIGSLAB

Laboratory Experiment 1

Page 1-4

generates a row vector of integers from 1 to 8. For increment other than unity, the following command can
be used:
>>x = 0:pi/3:5*pi
For negative increment
>>x = 5 : -1 : -4
2.4 Elementary Function
Some of the Matlab function automatically operate element by element on an array. For example,
exp(x) will return an array with each element equal to the exponential of the corresponding element of x.
The other function that operate element by element are given in table 1-5.
Table 1-5. Elementary Math Functions
abs
Absolute value
acos
Inverse cosine
acosh
Inverse hyperbolic cosine
angle
Phase angle
asin
Inverse sine
asinh
Inverse hyperbolic sine
atan
Inverse tangent
atanh
Inverse hyperbolic tangent
conj
complex conjugate
cos
Cosine
cosh
Hyperbolic cosine
exp
Exponential
fix
Round towards zero
floor
Round towards infinity
imag
Complex Imaginary part
log
Natural logarithm
log10
Common logarithm
real
Complex real part
rem
remainder after division
round
Round towards nearest integer
sign
Signum function
sinh
Hyperbolic sine
sqrt
Square root
tan
Tangent
tanh
Hyperbolic tangent
2.5 Logical Operators
Matlabs relational operators and logical operators also work on an element-by-element basis.
Relational operators compare two scalars and produce a 1 if the operation is true and a 0 if it is false. For
example, if you enter t = 17 > 55, MATLAB will respond with t =0. When used with two matrices,
relational operators compare corresponding matrix elements. For example, L = D < = X will check every
element of D against the corresponding element of X. If the element of D is less than or equal to the
corresponding element of X, the corresponding element of L will be 1. Otherwise, the corresponding
element of L will be zero.

SIGSLAB

Laboratory Experiment 1

Page 1-5

The logical operators & for logical AND, | for logical OR, and ~ for logical NOT all return 1 for
logical TRUE and 0 for logical FALSE.
To learn more about relational operators type help <=.
2.6 Script File
A script file is an ASCII file that contains a series of MATLAB command just as you would enter
them in MATLAB environment. Statement that begins with % is considered to be comment and are ignored
by MATLAB. The script file is created outside the MATLAB environment with any text editor or word
processor. Each script file should have a name that ends in .m The commands in the script file are
executed in the MATLAB environment by simply entering the name of the script file without the extension
.m
2.7 Creating Functions
Function files are m-files that are very similar to script files. The first major difference is that the
first line of a function file begins with the word function, followed by a statement identifying the name of
the function and the input and output argument in the form
function [output arguments] = function name( input arguments)
For example, suppose you want to create a new function called rms that computes the root mean
square of a list of numbers. The first line of your function file might look like function y = rms(v). The next
several lines should be comment line describing how to use rms. Later when you type help rms, MATLAB
will respond with these comment lines. The remaining line of the function file should look as they would in
a script file. Remember that the input argument v will be defined when the function is called.
The second major difference between function files and script files is that the variables generated
in function files are local to the function, whereas variables in script files are global. The function file to
produce the rms command might look as follows:
function y = rms(v)
% rms Root mean square
% rms(v) returns the root mean square of the elements
% of column vector v. If v is a matrix then
% rms(v) returns a row vector such that each element
% is the root mean square of the elements in the corresponding
% column of v.
vs = v.^2;
s = size(v);
y = sqrt(sum(vs)/s(1));

2.8 Control Flow


MATLAB control flow are given in table 1-6. The control flow command for, while, and if are
statements similar to those used in many computer languages to produce conditional statements or loops.
Every for, while, and if statements must be matched with an end statement. The break command can be used
to terminate the execution of a loop permanently.
The if statement can be used in conjunction with the nargin, nargout, and error functions to
perform error checking of a function. Inside a function file, nargin and nargout are equal to the number of
input and output arguments, respectively, that were used in function call. The command error(message)

SIGSLAB

Laboratory Experiment 1

Page 1-6

returns control to the keyboard and displays message. To find out more about for, while, break, if, and error
type help lang in the MATLAB prompt.
Table 1-6 Control Flow
break
Terminate execution of loop
else
used with if
elseif
used with if
and
Terminate the loop for, while, and if statement
error
Display message and abort function
for
Repeat statement a specified number of times
if
conditionally executed statements
return
return to invoking function
while
Repeat statements an indefinite number of times
2.8 Graphics
MATLAB can create high-resolution, publication-quality 2-D, 3-D, linear, log, semilog, polar, bar
chart and contour plots on plotters, dot-matrix printers, and laser printers. Some of the 2-D graph types are
plot, loglog, semilogx, semilogy, polar, and bar. The command grid adds a grid to the graph, and the
command title(text), xlabel(text), ylabel(text), and text(text) can be used for labeling and placing text
on the graph.
MATLAB provides automatic scaling. The command axis([xmin, xmax, ymin, ymax]) enforces
manual scaling.
Shown in table 1-7a-b are some of the useful commands in 2-D graphics
Table 1-7a Elementary X-Y graph
fill
Draw filled 2-D polygon
loglog
log-log scale plot
plot
linear plot
semilogx
semi-log scale plot
semilogy
semi-log scale plot
Table 1-7b Grap Annotation
grid
Grid lines
gtext
Mouse placement of text
text
Text annotation
title
Graph title
xlabel
x-axis label
ylabel
y-axis label
IV. Laboratory Exercise
4.1 Encode the following matrices in MATLAB.

a 11
A = a 21

a 31

SIGSLAB

a 12
a 22
a 32

a 13
a 23 =

a 33

2 5 6
4 4 3

1 3 5

b 11
B = b 21

b 31

Laboratory Experiment 1

b 12
b 22
b 32

b 13
b 23 =

b 33

1 5 6
4 2 3

2 3 5

Page 1-7

4.2 Evaluate the following using Matlab Expression :


4.2.1 AB
4.2.2 BA
4.2.3 A+B
4.2.4 A-B
4.2.5 A 1
4.2.6 A T
4.2.7 AA 1
a 11b11

4.2.8 a 21b 21
a b
31 31

a 11 / b 11

4.2.8 a 21 / b 21
a 31 / b 31
4.2.9 [a 11 b 21

a 12 b12
a 22 b 22
a 32 b 32

a 13 b13

a 23 b 23
a 33 b 33

a 13 / b 13

a 23 / b 23
a 33 / b 33
a 31 b 23 ]

a 12 / b 12
a 22 / b 22
a 32 / b 32

a 21 b 22

4.3 Generate a row vector n whose value is linearly increasing from 0 to 127.
4.4 Using the vector obtained in number 4.3, Generate a sinusoidal sequence, x[n], whose period is 25
samples.
4.5 Plot the sinusoidal sequence (continuous plot and discrete plot) and make the necessary label. Use
xlabel and ylabel.(abscissa - n, ordinate - x[n]). The continuous plot and the discrete should be
displayed in one screen.
4.6 Given a vector x whose values are complex, determine the magnitude and the corresponding phase. Use
the Matlab command angle and abs. To ensure that the angle is within - to range, use the Matlab
function unwrap. Plot the magnitude and phase with corresponding label. Use the function stem to plot
the magnitude and phase. The two graph should be shown in one screen. (Discrete plot - stem)
x = [1 i 2 + i 4 + i8 1 i]
4.7 Using for do loops, create a function that will calculate factorial of x, where the element of x is any
scalar integer. Call this function myfactorial.
4.8 Write a Matlab function that will calculate the Discrete Fourier transform of x[n]. Call this function
mydft. The function should be able to plot the Magnitude and the Phase response in one screen.
X( k ) =

N 1

x[ n]e

j2 nk
N

k = 0,1,2,..., N 1

n=0

4.9 Determine the DFT of the sinc function given below. Use the function in number 4.8 and Plot the
Magnitude and Phase Spectrum in one screen. The Magnitude should be a logarithmic scale.
x = sin c([ 51
: / 10:5])

SIGSLAB

Laboratory Experiment 1

Page 1-8

You might also like