0% found this document useful (0 votes)
82 views33 pages

Final Matlab (DSP Fyl) TOP

MATLAB is a high-performance technical computing language. It integrates computation, visualization, and programming. MATLAB is used for math and computation, algorithm development, data analysis, and more. The MATLAB desktop provides tools like the command window, workspace browser, and editor for coding and running scripts. Key commands include plotting functions like plot, bar, stem; array creation like zeros and ones; mathematical functions like exp; and filtering functions like conv and filter.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views33 pages

Final Matlab (DSP Fyl) TOP

MATLAB is a high-performance technical computing language. It integrates computation, visualization, and programming. MATLAB is used for math and computation, algorithm development, data analysis, and more. The MATLAB desktop provides tools like the command window, workspace browser, and editor for coding and running scripts. Key commands include plotting functions like plot, bar, stem; array creation like zeros and ones; mathematical functions like exp; and filtering functions like conv and filter.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

MATLAB

1. INTRODUCTION OF MATLAB
Aim: To study important commands of MATLAB software.
Apparatus : PC having MATLAB software.
1.Introduction : MATLAB is a high-performance language for technical computing. It
integrates computation, visualization, and programming in an easy-to-use environment where
problems and solutions are expressed in familiar mathematical notation.
Typical uses include Math and computation, Algorithm development, Data acquisition,
Modeling, simulation, and prototyping, Data analysis, exploration, and visualization,
Scientific and engineering graphics, Application development, including graphical user
interface building.
MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program
in a scalar non interactive language such as C or Fortran. The name MATLAB stands
for matrix laboratory.
Starting MATLAB on Windows platforms, start MATLAB by double-clicking the MATLAB
shortcut icon on your Windows desktop.
Quitting MATLAB: To end your MATLAB session, select File > Exit MATLAB in the
desktop, or type quit in the Command Window. You can run a script file named finish.m each
time MATLAB quits that, for example, executes functions to save the workspace.
2. MATLAB desktop: On starting MATLAB the MATLAB desktop appears, containing
tools (graphical user interfaces ) for managing files , variables and applications associated
with MATLAB. It contains :
(i) Command Window and Command History
Command Window : Use the Command Window to enter variables and to run functions and
M-file scripts. Press the up arrow key to recall a statement previously typed. Edit the
statement as needed and then press Enter to run it.

1
1149888

MATLAB

Command History : Statements entered in the Command Window are logged in the
Command History. From the Command History, previously run statements can be viewed,
copied and executed. M-file can be created from selected statements.
(ii) Current Directory Browser and Search Path :
MATLAB file operations use the current directory and the search path as reference points.
Any file required to run must either be in the current directory or on the search path.
(iii) Workspace Browser and Array Editor :
The MATLAB workspace consists of the set of variables(named arrays) built up during a
MATLAB session and stored in memory. The variables can be added to theworkspace by
using functions, running M-files, and loading saved workspaces. To delete variables from
theworkspace, select the variables and select Edit > Delete. Array Editor : Double-click a
variable in the Workspace browser, or use open var variable name, to see it in the Array
Editor. Use the Array Editor to view and edit a visual representation of variables in the
workspace.
(iv) Editor/Debugger :
Editor/Debugger is used to create and debug M-files, which are programs to run MATLAB
functions. The Editor/Debugger provides a graphical user interface for text editing, as well as
for M-file debugging. To create or edit an M-file use File > New or File > Open, or use the
edit function.
THE IMPORTANT COMMANDS/ FUNCTIONS ARE AS BELOW :
1. clc (Remove items from workspace, freeing up system memory): clears all input and
output from the Command Window display, giving "clean screen." After using clc, the scroll
bar cannot be used to seethe history of functions, but still the up arrow can be used to recall
statements from the command history.
2. close (Remove specified figure): close deletes the current figure or the specified figure(s).
It optionally returns the status of the close operation.
3. xlabel, ylabel, zlabel (Label x-, y-, and z-axis) : Each axes graphics object can have one
label for the x-, y-, and z-axis. The label appears beneath its respective axis in a twodimensional plot and to the side or beneath the axis in a three-dimensional plot.
2
1149888

MATLAB

xlabel('string') labels the x-axis of the current axes.


ylabel(...) and zlabel(...) label the y-axis and z-axis, respectively, of the current axes.
4. title(Add title to current axes) : Each axes graphics object can have one title. The title is
located at the top and in the center of the axes.
title('string') outputs the string at the top and in the center of the current axes.
5. figure(create figure graphics object) : figure creates figure graphics objects. Figure
objects are the individual windows on the screen in which MATLAB displays graphical
output.
6. subplot (Create axes in tiled positions): subplot divides the current figure into
rectangular panes that are numbered row wise. Each pane contains an axes object.
Subsequent plots are output to the current pane.
h = subplot(m,n,p) or subplot(mnp) breaks the figure window into an m-by-n matrix of
small axes, selects the pth axes object for the current plot, and returns the axes handle. The
axes are counted along the top row of the figure window, then the second row, etc.
For example,

subplot(2,1,1), plot(income)

subplot(2,1,2), plot(outgo)
plots income on the top half of the window and outgo on the bottom half.
7. stem (Plot discrete sequence data): A two-dimensional stem plot displays data as lines
extending from a baseline along the x-axis. A circle (the default) or other marker whose yposition represents the data value terminates each stem.
stem(Y)

Plots the data sequence Y as stems that extend from equally spaced and

automatically generated values along the x-axis. When Y is a matrix, stem plots all elements
in a row against the same x value.
stem(X,Y) plots X versus the columns of Y. X and Y must be vectors or matrices of the same
size. Additionally, X can be a row or a column vector and Y a matrix with length(X) rows.
8. bar(Plot bar graph (vertical and horizontal)): A bar graph displays the values in a
vector or matrix as horizontal or vertical bars.
3
1149888

MATLAB

bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the bars produced by
the elements in each row. The x-axis scale ranges from 1 up to length(Y) when Y is a vector,
and 1 to size(Y,1), which is the number of rows, when Y is a matrix.
barh(...) and h = barh(...) create horizontal bars. Y determines the bar length. The vector x is
a vector defining the y-axis intervals for horizontal bars.
9.plot ( 2-D line plot): plot(Y) Plots the columns of Y versus their index if Y is a real
number. If Y is complex, plot(Y) is equivalent to plot(real(Y), imag(Y)). In all other uses of
plot, the imaginary component is ignored.
plot(X1,Y1,...) Plots all lines defined by Xn versus Yn pairs. If only Xn or Yn is a matrix, the
vector isplotted versus the rows or columns of the matrix, depending on whether the vector's
row or column dimension matches the matrix. If Xn is a scalar and Yn is a vector,
disconnected line objects are created and plotted as discrete points vertically at Xn.
10.input (Request user input): The response to the input prompt can be any MATLAB
expression, which is evaluated using the variables in the current workspace.
user_entry = input('prompt') Displays prompt as a prompt on the screen, waits for input
from the keyboard, and returns the value entered in user_entry. user_entry = input('prompt',
's') returns the entered string as a text variable rather than as a variable name or numerical
value.
11.zeros (Create array of all zeros):
B = zeros(n) Returns an n-by-n matrix of zeros. An error message appears if n is not a scalar.
12. ones (Create array of all ones):
Y = ones(n) Rreturns an n-by-n matrix of 1s. An error message appears if n is not a scalar.
13. exp (Exponential) :Y = exp(X) : The exp function is an elementary function that
operates element-wise on arrays. Its domain includes complex numbers. Y = exp(X) returns
the exponential for each element of X.
14. disp (Display text or array) :disp(X) Displays an array, without printing the array name.
If X contains a text string, the string is displayed. Another way to display an array on the

4
1149888

MATLAB

screen is to type its name, but this prints a leading "X=," which is not always desirable. Note
that disp does not display empty arrays.
15. conv (Convolution and polynomial multiplication) :w = conv(u,v) convolves vectors u
and v. Algebraically, convolution is the same operation as multiplying the polynomials whose
coefficients are the elements of u and v.
16. xcorr (Cross-correlation) : c = xcorr(x,y) returns the cross-correlation sequence in a
length 2*N-1 vector, where x and y are length N vectors (N>1). If x and y are not the same
length, the shorter vector is zero-padded to the length of the longer vector.
17. filter (1-D digital filter) :y = filter(b,a,X) filters the data in vector X with the filter
described by numerator coefficient vector b and denominator coefficient vector a. If a(1) is
not equal to 1, filter normalizes the filter coefficients by a(1). If a(1) equals 0, filter returns an
error.
18. poly (Polynomial with specified roots) :
r = roots(p) which returns a column vector whose elements are the roots of the polynomial
specified by the coefficients row vector p. For vectors, roots and poly are inverse functions of
each other, up to ordering, scaling, and round off error.
19.

tf(Convert

unconstrained

MPC

controller

to

linear

transfer

function)

:sys=tf(MPCobj)
The tf function computes the transfer function of the linear controller ss(MPCobj)as an LTI
system in tf form corresponding to the MPC controller when the constraints are not active.
The purpose is to use the linear equivalent control in Control System Toolbox for sensitivity
and other linear analysis.
20.freqz (Frequency response of filter ) :[h,w] = freqz(ha) returns the frequency response
vector h and the corresponding frequency vector w for the adaptive filter ha. When ha is a
vector of adaptive filters, freq z returns the matrix h. Each column of h corresponds to one
filter in the vector ha.
21. abs (Absolute value and complex magnitude) :
abs(X) returns an array Y such that each element of Y is the absolute value of the
corresponding element of X.
5
1149888

MATLAB

22. fft (Discrete Fourier transform) :Y = fft(X)


Y = fft(X) returns the discrete Fourier transform (DFT) of vector X, computed with a fast
Fourier transform (FFT) algorithm.
23. mod (Modulus after division) :M = mod(X,Y)
returns X - n.*Y where n = floor(X./Y). If Y is not an integer and the quotient X./Y is within
round off error of an integer, then n is that integer. The inputs X and Y must be real arrays of
the same size, or real scalars.
24. sqrt (Square root) :B = sqrt(X)
returns the square root of each element of the array X. For the elements of X that are negative
or complex, sqrt(X) produces complex results.
25. ceil (Round toward infinity) :B = ceil(A)
rounds the elements of A to the nearest integers greater than or equal to A. For complex A, the
imaginary and real parts are rounded independently.
26. fir1(Window-based finite impulse response filter design) :
b = fir1(n,Wn) returns row vector b containing the n+1 coefficients of an order n low pass
FIR filter. This is a Hamming-window based, linear-phase filter with normalized cutoff
frequency Wn. The output filter coefficients, b, are ordered in descending powers of z.
27.

buttord

(Butterworth

filter

order

and

cutoff

frequency)

:[n,Wn]

buttord(Wp,Ws,Rp,Rs)
returns the lowest order, n, of the digital Butterworth filter that loses no more than Rp dB in
the pass band and has at least Rs dB of attenuation in the stop band. The scalar (or vector) of
corresponding cutoff frequencies, Wn, is also returned. Use the output arguments n and Wn
in butter.
28. fliplr (Flip matrix left to right) :B = fliplr(A)
returns A with columns flipped in the left-right direction, that is, about a vertical axis. If Ais a
row vector, then fliplr(A) returns a vector of the same length with the order of its elements
reversed. If A is a column vector, then fliplr(A) simply returns A.
6
1149888

MATLAB

29. min ( Smallest elements in array) :


C = min(A) returns the smallest elements along different dimensions of an array. If A is a
vector, min(A) returns the smallest element in A. If A is a matrix, min(A) treats the columns
of A as vectors, returning a row vector containing the minimum element from each column. If
A is a multidimensional array, min operates along the first nonsingleton dimension.
30. max ( Largest elements in array) :
C = max(A) returns the largest elements along different dimensions of an array. If A is a
vector, max(A)returns the largest element in A. If A is a matrix, max(A) treats the columns of
A as vectors, returning a row vector containing the maximum element from each column. If A
is a multidimensional array, max(A)treats the values along the first non-singleton dimension
as vectors, returning the maximum value of each vector.
31. find (Find indices and values of nonzero elements) :ind = find(X)
locates all nonzero elements of array X, and returns the linear indices of those elements in
vector in d. If X is a row vector, then in d is a row vector; otherwise, in d is a column vector.
If X contains no nonzero elements or is an empty array, then in d is an empty array.
32. residuez (z-transform partial-fraction expansion ) :
residue z converts a discrete time system, expressed as the ratio of two polynomials, to partial
fraction expansion, or residue, form. It also converts the partial fraction expansion back to the
original polynomial coefficients.
33. angle (Phase angle) :
P = angle(Z) returns the phase angles, in radians, for each element of complex array Z. The
angles lie between + and .
34. log (Natural logarithm ) :
Y = log(X) returns the natural logarithm of the elements of X. For complex or negative z,
where z = x+y*i, the complex logarithm is returned.

7
1149888

MATLAB

2. PROGRAM 1
AIM: Write a program to generate ramp function, unit step function, rising exponential
function and decaying exponential function.
(A) RAMP FUNCTION
THEORY:The ramp function is a unary real function, easily computable as the mean of
its independent variable and its absolute value. This function is applied in engineering (e.g.,
in the theory of DSP). The name ramp function can be derived by the look of its graph.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0
CODING:
FOR CONTINOUS SIGNAL:
x=[0:10]
x=t
plot(x,t)
FOR DISCRETE SIGNAL:
x=[0:10]
x=n
stem(x,n)

8
1149888

MATLAB

OUTPUT WAVEFORM:
In Continuous Form:

Fig 1.1Continuous Time signal of Ramp


function

In Discrete Form:

Fig 1.2 Discrete Time Signal of Ramp


Function

9
1149888

MATLAB

(B) UNIT STEP FUNCTION


THEORY: The Heaviside step function, or the unit step function, usually denoted by H (but
sometimes u or ), is a discontinuous function whose value is zero for negative argument
and one for positive argument.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0.
CODING:
FOR CONTINOUS SIGNAL:
y=1
x=[0:0.05:20]
plot(x,y)
FOR DISCRETE SIGNAL:
n=1
x=[0:0.05:20]
stem(x,n)

10
1149888

MATLAB

OUTPUT WAVEFORM:
Continuous Form :

Discrete Form:

Fig 1.3 Continuous Time Signal of Unit Step


Function

Fig 1.4 Discrete Time Signal of Unit


Step Function

11
1149888

MATLAB

(C) RISING EXPONENTIAL FUNCTION:


EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0
THEORY: In mathematics, the exponential function is the function ex, where e is the number
(approximately 2.718281828) such that the function ex is its own derivative. The exponential
function is used to model a relationship in which a constant change in the independent
variable gives the same proportional change (i.e. percentage increase or decrease) in the
dependent variable.
CODING:
For continuous time signal:
t=[0:100]
y=exp(t)
plot(y)
title('Rising exponential function')
For discrete time signal:
n=[0:100]
y=exp(n)
stem(y)
title('Rising exponential function')

12
1149888

MATLAB

OUTPUT WAVEFORM:
For Continuous Time Signal:

Fig 1.5 Continuous Time Signal of Rising


Exponential Function

For discrete time signal:

Fig 1.6 Discrete Time Signal of Rising Exponential


Function

13
1149888

MATLAB

(D) DECAYING EXPONENTIAL FUNCTION


EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0
THEORY: In mathematics, the exponential function is the function ex, where e is the number
(approximately 2.718281828) such that the function ex is its own derivative. The exponential
function is used to model a relationship in which a constant change in the independent
variable gives the same proportional change (i.e. percentage increase or decrease) in the
dependent variable.
CODING:
For Continuous time:
t=[0:100]
y=exp(-t)
plot(y)
title('Decaying exponential function')
For discrete time signal:
n=[0:100]
y=exp(-n)
plot(y)
title('Decaying exponential function')

14
1149888

MATLAB

OUTPUT WAVEFORM:
For Continuous Signal:

Fig 1.7 Continuous Time Signal of Decaying


Exponential Function

For Discrete Signal:

Fig 1.8 Discrete Time Signal of Decaying


Exponential Function

3. PROGRAM 2
15
1149888

MATLAB

AIM: Write a program to find the convolution of two functions.


EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0
THEORY:

In mathematics and,

in

particular, functional

analysis, convolution is

a mathematical operation on two functions f and g, producing a third function that is typically
viewed as a modified version of one of the original functions, giving the area overlap
between the two functions as a function of the amount that one of the original functions
is translated. Convolution is similar to cross-correlation. It has applications that
include probability, statistics, computer

vision, image and signal

processing, electrical

engineering, and differential equations.


CODING:
x=[ 1 2]
h=[1 2 4]
y=convn(x,h)
subplot(3,1,1)
stem(x)
xlabel('(a) ---------------> n')
ylabel('Amplitude')
subplot(3,1,2)
stem(h)
xlabel('(b) ---------------> n')
ylabel('Amplitude')
subplot(3,1,3)
stem(y)
xlabel('(c) ---------------> n')
ylabel('Amplitude')

OUTPUT WAVEFORMS
16
1149888

MATLAB

4. PROGRAM
Fig 2.1 Convolution
of Two
Signals

AIM: Write a program to plot multidata in a single plot with matlab.


EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0.
CODING:
x=[0:pi/10:2*pi];
y1=2*cos(x);
y2=3*cos(x);
y3=cos(x);
plot(x,y1,'r+-',x,y2,'-',x,y3,'g+-')
xlabel('0 to 2pi-->');
ylabel('amplitude');
legend('2cos(x)', '3cos(x)','cos(x)');

17
1149888

MATLAB

OUTPUT WAVEFORMS:

Fig 3.1 Multi data In a


single plot
18
1149888

MATLAB

5. PROGRAM 4
AIM: Write a program to add two sine functions and plot them.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0
CODING:
t=[0:0.001:1];
f1=2;
f2=3;
x1=sin(2*f1*t);
x2=sin(2*f2*t);
subplot(3,2,1);
plot(t,x1,t,x2,'r');
xlabel('t-->')
ylabel('amplitude-->');
y=x1+x2;
subplot(3,2,2);
plot(t,y,'c');
xlabel('t-->')
ylabel('amplitude-->');

19
1149888

MATLAB

OUTPUT WAVEFORMS:

Fig 4 .1 Addition of Two


Sine Waves

20
1149888

MATLAB

6. PROGRAM 5
AIM: Write a program of folding and multiplication of two sine functions and plot them.
EQUIPMENT AND SOFTWARE: Personal Computer loaded with MATLAB 7.0.
CODING:
x=[0:0.001:1];
l=length(x);
f1=1;
f2=3;
x1=sin(2*f1*x);
x2=sin(2*f2*x);
subplot(3,2,1);
plot(x,x1,'b',x,x2,'r');
xlabel('t-->');
ylabel('amplitude-->');
title('two sine waves');
x3=(x1.*x2);
subplot(3,2,2);
plot(x,x3);
title('Multiplication of two sine waves');
xlabel('t-->');
ylabel('amplitude-->');
x=[-1:0.001:0];
x4=sin(2*pi*f1*(-x));
21
1149888

MATLAB

x5=sin(2*pi*f2*(-x));
subplot(3,2,3);
plot(x,x4,'b',x,x5,'r');
title('Folding of signals');
xlabel('t-->');
ylabel('amplitude-->');

OUTPUT WAVEFORMS:

Fig 5.1 Folding and Multiplication of Two


sine22
Waves

1149888

MATLAB

7. PROGRAM 6
AIM: Write a program for computing Discrete Fourier Transform(DFT).
EQUIPMENT AND SOFTWARE: Personal Computer loaded with MATLAB 7.0.
CODING:
x=input('Enter the sequence:'); %x=[0 1 2 3 4 5 6 7]
n=input('Enter the length of Fourier Transform:'); %n=8 has to be same as the length of the
sequence
x=fft(x,n);
stem(x);
ylabel('imaginary axis-->');
xlabel('real axis-->');
title('Exponential sequence');
disp('DFT is x=');

23
1149888

MATLAB

OUTPUT WAVEFORMS:

Fig 6 .1 Discrete Fourier


Transform
24
1149888

MATLAB

8. PROGRAM 7
AIM: Write a program for computing Inverse Discrete Fourier Transform(IDFT).
EQUIPMENT AND SOFTWARE: Personal Computer loaded with MATLAB 7.0.
CODING:
x=input('Enter the length of DFT'); %for best results in power of 2
t=0:pi/x:pi;
num=[0.05 0.033 0.008];
den=[0.06 4 1]
trans=tf(num,den);
[freq,w]=freqz(num,den,x);
grid on;
subplot(2,1,1);
plot(abs(freq));
ylabel('Magnitude');
xlabel('Frequency index');
title('Magnitude Response');

25
1149888

MATLAB

OUTPUT WAVEFORMS:

26
1149888

MATLAB

Fig 7.1 Inverse Discrete Fourier


Transform

9. PROGRAM 8
AIM: Write a program for computing Inverse Z- Transform using Residuez Function.
27
1149888

MATLAB

EQUIPMENT AND SOFTWARE: Personal Computer loaded with MATLAB 7.0.


CODING:
b=[1 0.5 -0.2];
a=[1 0.5 -0.25];
z=residuez(b,a);
subplot(2,2,1);
stem(b);
ylabel('(a)-->');
xlabel('(z)-->');
disp('Output is');

OUTPUT WAVEFORMS:
28
1149888

MATLAB

Fig 8.1 Inverse Z- Transform using


Residue Method

29
1149888

MATLAB

10.PROGRAM 9
AIM: Write a program for computing Circular Covolution.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB 7.0
CODING:
g=[1 -3 4 2 0 -2];
h=[3 0 1 -1 2 1];
for i=1:6,y(i)=0;
for k=1:6,z=mod(6-k+i,6)+1;
y(i)=y(i)+g(z)*h(k);
end
end
disp('The resultant Signal is');
stem(y);
ylabel('Amplitude-->');
xlabel('n-->');
title('Circular Convolution');

30
1149888

MATLAB

OUTPUT WAVEFORMS:

Fig 9.1 Computation of Circular


Convolution

31
1149888

MATLAB

11.PROGRAM 10
AIM:

Write a program for finding the magnitude and phase response of LTI System

describes by the system function h(z).


EQUIPMENT AND SOFTWARE: Personal Computer loaded with MATLAB 7.0.
CODING:
w=[0:1:500]*pi/500; %[0,pi] axis divided into 501 points
h=exp(j*w)./(exp(j*w)-0.9*ones(1,501));
magh=abs(h);
angh=angle(h);
subplot(2,1,1);
plot(w/pi,magh);
grid;
ylabel('|h|-->');
xlabel('Frequency in pi units');
title('Magnitude Response');
subplot(2,1,2);
plot(w/pi,angh/pi);
grid;
ylabel('Phase in pi radians');
xlabel('Frequency in pi units');
title('Phase Response');

32
1149888

MATLAB

OUTPUT WAVEFORMS:

Fig 10.1 Magnitude and Phase Response


of LTI System

33
1149888

You might also like