You are on page 1of 234

MATLAB PROGRAM TO IMPLEMENT DISCRETE

FOURIER TRANSFORM
%DFT
close all;
clear all;
N=input('Howmany point DFT do you want?');
x2=input('Enter the sequence=');
n2=length(x2);
c= zeros(N);
x2=[x2 zeros(1,N-n2)];
for k=1:N
for n=1:N
w=exp((-2*pi*i*(k-1)*(n-1))/N);
%prev.step=>evaluating w-matrix
x(n)=w;
end
c(k,:)=x;
end
r=[c]*[x2']
%plotting magnitude and angle
subplot(211)
stem(abs(r));
title('DFT-absolute value');
subplot(212)
stem(angle(r));
title('DFT-angle');
OUTPUT WAVEFORM

Posted by Quizzing Champion at 12:02 AM


Email ThisBlogThis!Share to TwitterShare to Facebook
Labels: DFT, DIGITAL SIGN
Search R20

MATLAB
Mathematics
Fourier Analysis and Filtering

fft
Fast Fourier transform
Syntax
Y = fft(x)
Y = fft(X,n)

Y = fft(X,[],dim)
Y = fft(X,n,dim)
Definitions
The functions Y = fft(x) and y = ifft(X) implement the transform
and inverse transform pair given for vectors of length N by:

where

is an Nth root of unity.


Description
Y = fft(x) returns the discrete Fourier transform (DFT) of vector x,
computed with a fast Fourier transform (FFT) algorithm.
If the input X is a matrix, Y = fft(X) returns the Fourier transform
of each column of the matrix.
If the input X is a multidimensional array, fft operates on the first
nonsingleton dimension.
Y = fft(X,n) returns the n-point DFT. fft(X) is equivalent to fft(X,
n) where n is the size of X in the first nonsingleton dimension. If
the length of X is less than n, X is padded with trailing zeros to
length n. If the length of X is greater than n, the sequence X is
truncated. When X is a matrix, the length of the columns are
adjusted in the same manner.

Y = fft(X,[],dim) and Y = fft(X,n,dim) applies the FFT operation


across the dimension dim.
Examples
A common use of Fourier transforms is to find the frequency
components of a signal buried in a noisy time domain signal.
Consider data sampled at 1000 Hz. Form a signal containing a 50
Hz sinusoid of amplitude 0.7 and 120 Hz sinusoid of amplitude 1
and corrupt it with some zero-mean random noise:
Fs = 1000;
% Sampling frequency
T = 1/Fs;
% Sample time
L = 1000;
% Length of signal
t = (0:L-1)*T;
% Time vector
% Sum of a 50 Hz sinusoid and a 120 Hz sinusoid
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
y = x + 2*randn(size(t)); % Sinusoids plus noise
plot(Fs*t(1:50),y(1:50))
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('time (milliseconds)')

It is difficult to identify the frequency components by looking at


the original signal. Converting to the frequency domain, the
discrete Fourier transform of the noisy signal y is found by taking
the fast Fourier transform (FFT):
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
plot(f,2*abs(Y(1:NFFT/2+1)))
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')

The main reason the amplitudes are not exactly at 0.7 and 1 is
because of the noise. Several executions of this code (including
recomputation of y) will produce different approximations to 0.7
and 1. The other reason is that you have a finite length signal.
Increasing L from 1000 to 10000 in the example above will
produce much better approximations on average.
Data Type Support
fft supports inputs of data types double and single. If you call fft
with the syntax y = fft(X, ...), the output y has the same data type
as the input X.
More About
expand all
Algorithms

References
[1] Cooley, J. W. and J. W. Tukey, "An Algorithm for the Machine
Computation of the Complex Fourier Series,"Mathematics of
Computation, Vol. 19, April 1965, pp. 297-301.
[2] Duhamel, P. and M. Vetterli, "Fast Fourier Transforms: A
Tutorial Review and a State of the Art," Signal Processing, Vol.
19, April 1990, pp. 259-299.
[3] FFTW (http://www.fftw.org)
[4] Frigo, M. and S. G. Johnson, "FFTW: An Adaptive Software
Architecture for the FFT,"Proceedings of the International
Conference on Acoustics, Speech, and Signal Processing, Vol. 3,
1998, pp. 1381-1384.
[5] Oppenheim, A. V. and R. W. Schafer, Discrete-Time Signal
Processing, Prentice-Hall, 1989, p. 611.
[6] Oppenheim, A. V. and R. W. Schafer, Discrete-Time Signal
Processing, Prentice-Hall, 1989, p. 619.
[7] Rader, C. M., "Discrete Fourier Transforms when the Number
of Data Samples Is Prime," Proceedings of the IEEE, Vol. 56, June
1968, pp. 1107-1108.
See Also
dftmtx | fft2 | fftn | fftshift | fftw | filter | freqz | ifft
Was this topic helpful?
Try MATLAB, Simulink, and Other Products
Get trial now

Join the conversation

Preventing Piracy
Privacy Policy
Trademarks
Patents
Site Help

1994-2012 The MathWorks, Inc.


Search R20

Signal Processing Toolbox


Transforms

fwht
Fast WalshHadamard transform
Syntax
y = fwht(x)
y = fwht(x,n)
y = fwht(x,n,ordering)
Description
y = fwht(x) returns the coefficients of the discrete Walsh
Hadamard transform of the input x. If x is a matrix, the FWHT is
calculated on each column of x. The FWHT operates only on
signals with length equal to a power of 2. If the length of x is less
than a power of 2, its length is padded with zeros to the next
greater power of two before processing.

y = fwht(x,n) returns the n-point discrete WalshHadamard


transform, where n must be a power of 2. x and n must be the same
length. If x is longer than n, x is truncated; if x is shorter than n, x
is padded with zeros.
y = fwht(x,n,ordering) specifies the ordering to use for the returned
WalshHadamard transform coefficients. To specify ordering, you
must enter a value for the length n or, to use the default behavior,
specify an empty vector [] for n. Valid values for ordering are the
following strings:
Ordering

Description

'sequency' Coefficients in order of increasing sequency value,


where each row has an additional zero crossing. This is
the default ordering.
'hadamard' Coefficients in normal Hadamard order.
'dyadic'

Coefficients in Gray code order, where a single bit


change occurs from one coefficient to the next.

For more information on the Walsh functions and ordering, see


WalshHadamard Transform.
Examples
This example shows a simple input signal and the resulting
transformed signal.
x = [19 -1 11 -9 -7 13 -15 5];
y = fwht(x);
y contains nonzero values at these locations: 0, 1, 3, and 6. By
forming the Walsh functions with the sequency values of 0, 1, 3,
and 6, we can recreate x, as follows.
w0 = [1 1 1 1 1 1 1 1];

w1 = [1 1 1 1 -1 -1 -1 -1];
w3 = [1 1 -1 -1 1 1 -1 -1];
w6 = [1 -1 1 -1 -1 1 -1 1];
w = 2*w0 + 3*w1 + 4*w3 + 10*w6;
y1=fwht(w);
x1 = ifwht(y);
More About
expand all
Algorithms
References
[1] Beauchamp, K.G., Applications of Walsh and Related
Functions, Academic Press, 1984.
[2] Beer, T., Walsh Transforms, American Journal of Physics,
Volume 49, Issue 5, May 1981.
See Also
dct | fft | idct | ifft | ifwht
Search R20

Signal Processing Toolbox


Transforms

ifwht
Inverse Fast WalshHadamard transform

Syntax
y = iwht(x)
y = ifwht(x,n)
y = ifwht(x,n,ordering)
Description
y = iwht(x) returns the coefficients of the inverse discrete fast
WalshHadamard transform of the input x. If x is a matrix, the
inverse fast Walsh-Hadamard tranform is calculated on each
column of x. The inverse fast Walsh-Hadamard tranform operates
only on signals with length equal to a power of 2. If the length of x
is less than a power of 2, its length is padded with zeros to the next
greater power of two before processing.
y = ifwht(x,n) returns the n-point inverse discrete Walsh
Hadamard transform, where n must be a power of 2.
y = ifwht(x,n,ordering) specifies the ordering to use for the
returned inverse WalshHadamard transform coefficients. To
specify ordering, you must enter a value for the length n or, to use
the default behavior, specify an empty vector [] for n. Valid values
for ordering are the following strings:
Ordering

Description

'sequency' Coefficients in order of ascending sequency value,


where each row has an additional zero crossing. This is
the default ordering.
'hadamard' Coefficients in normal Hadamard order.
'dyadic'

Coefficients in Gray code order, where a single bit


change occurs from one coefficient to the next.

More About
expand all
Algorithms
References
[1] Beauchamp, K.G., Applications of Walsh and Related
Functions, Academic Press, 1984.
[2] Beer, T., Walsh Transforms, American Journal of Physics,
Volume 49, Issue 5, May 1981.
See Also
dct | fft | fwht | idct | ifft
Was this topic helpful?
Try MATLAB, Simulink, and Other Products
Get trial now

Join the conversation

Preventing Piracy
Privacy Policy
Trademarks
Patents
Site Help

1994-2012 The MathWorks, Inc.

The Haar wavelet transform


Kristian Sandberg
Dept. of Applied Mathematics
University of Colorado at Boulder

A fractal along with a two level


Haar (standard) decomposition.
Image source: Carlson's Fractal
Gallery.
1 Goal
The goals with this lab are:
1.
Understand the properties of the Haar basis.
2.
Understand the averaging and differencing technique and
how it relates to a wavelet decomposition.
3.

Use the Haar transform to compress and de-noise one


dimensional signals and images.
2 Introduction
This lab will illustrate some fundamental concepts about wavelets
and multiresolution theory. Most examples and definitions will be
made with respect to the Haar scaling function and the Haar
wavelet. However, the concepts covered in this lab are true for
more ``advanced'' wavelets such as the Daubechies wavelets.
3 The Haar basis
Definition 1 (The Haar scaling function) Let
defined by

be
(1)

Define

as
(2)

Define the vector space Vj as


(3)

where

denotes the linear span.

The index j refers to dilation and i refers to translation.

Warning! This definition may be different in different texts!


Sometimes one defines the scaling function for negative integers as
well and uses a different sign convention. Whenever you use a text
on wavelets, make sure you know what sign convention is being
used.
The constant
is chosen such that
.
If one considers the scaling function on other intervals than [0,1],
the normalization constant will change.
Exercise 1: The Haar scaling function
a) Using, e.g., the Matlab functions haarscale.m and haargrid.m,
plot the basis vectors for Vj for j=0,1 and 2. Describe the
significance of the index j in Vj and the significance of the index i
in

when j is fixed.

b) Claim: The following property holds for Vj:


(4)

Based on your plots in a) above, convince yourself (and the reader


of your lab report) that this property holds for the Haar scaling
function. (If you see this relation written in ``the opposite
direction'' in some text, they used a different sign convention. The
relation given above is consistent with Definition 1.)
Definition 2 (The Haar wavelet function) Let
defined by

be

(5)

Define

as
(6)

Define the vector space Wj


(7)

where

denotes the linear span.

Warning! This definition may be different in different texts!


Sometimes one defines the wavelet function for negative integers
as well and uses a different sign convention. Whenever you use a
text on wavelets, make sure you know what sign convention is
being used.
Again, the constant

is chosen such that

. If one considers the wavelet function


on other intervals than [0,1], the normalization constant will
change.
Exercise 2: The Haar wavelet
a) Using, e.g., the Matlab functions haargrid.m and haarwavelet.m,
plot the basis vectors for Wj for j=0,1 and 2. Describe the

significance of the index j in Wj and the significance of the index i


in

when j is fixed.

b) Claim: The following property holds for Wj:


(8)

Based on your plots in a) above, convince yourself (and the reader


of your lab report) that this property holds for the Haar wavelet
function. (If you see this relation written in ``the opposite
direction'' in some text, they used a different sign convention. The
relation given above is consistent with Definition 2.)
c) A standard argument for using wavelets rather than the Fourier
basis for signal processing is that the Haar wavelet is localized. By
looking at your plots from a) above, can you see why the Haar
wavelet is called a ``localized'' function? Is the Fourier basis
localized?
4 The structure of the Haar basis
The Haar basis (and other wavelet basis) has the very important
property that
(9)

This property is explored in the following exercise.


Exercise 3: The relation between Vj and Wj
Using, e.g., the Matlab functions haargrid.m and haarwavelet.m,
produce a few plots that illustrate the following relation:
(10)

(The formulation of this exercise is very vague. However, the


purpose is to visualize the important relation
your imagination to do this.)

. Use

5 Expansion of a signal in an ON-basis


Let
denote a finite signal with N samples (cf. an Ndimensional vector) given by
(11)

Let

be an ON-basis in

.Then
(12)

Let us first review how this was used for Fourier analyzing a signal
and then see how this can be used for wavelet expansion of a
signal.
5.1 Review of Fourier analyzing a signal
Let
(13)

Denote the (n+1):th element of the vk vector as vk[n]. Then f can be


expanded as in (12) with

(14)

where * denotes complex conjugation. Numerically, we compute


<f,vk> by using the Fast Fourier Transform.
5.2 Wavelet transformation of a signal
In this example we consider a signal with 8 samples for clarity.
However, the procedure can be generalized to any finite signal.
The analysis simplifies if the length (dimension) of the signal is 2 k
for some positive integer k.
Let
and expand this signal into
spanned by the basis vectors according to Definitions 1 and 2
(discretized). Then

(15)

The correspondence to Fourier expanding a signal is now to


compute the inner products
and
. In principle,
we could do this by evaluating an integral (or a sum in the discrete
case). In practice, computation of the inner products for a wavelet
basis is done as illustrated by the following example.
5.2.1 Example: Averaging and differencing of a finite signal

Consider f=(2,5,8,9,7,4,-1,1). We wish to expand this signal in the


Haar basis according to (15). In practice, we do this by performing
the following steps:
Step 1:

Step 2:

Step 3:

The numbers in the final vector are the coefficients in the


expansion (15). You probably notice the pattern, we add/subtract a
pair of numbers, divide by the normalization factor
and
between every step we don't touch the last elements of the vector.
This procedure is called ``averaging and differencing''. In the next
section, we will study this example in more depth and see what we
really did mathematically.
5.2.2 The mathematics of averaging and differencing
The example in the previous section shows the steps that we want
to implement when we code up a one dimensional Haar wavelet
transform. When we consider two dimensional signals (images) we

will see that all we need to do is to act with the one dimensional
transform on each row of the image followed by a transformation
of each column of the image. Hence, the above example should
serve as a guide for programming your own Haar wavelet
transform later on.
Although the example above may be a good illustration of how the
Haar transform is coded, it is not that clear how the ``averaging
and differencing'' technique actually relates to the more
mathematical description in (15). The next paragraph will go
through the same steps as in the example above, but try to explain
what really was done mathematically.
We still consider the signal f=(2,5,8,9,7,4,-1,1). The coefficients of
the original signal are the coefficients of the vector f expanded in
V3, i.e.,
, etc. Recall that
3
the basis vectors of V are translation of the Haar mother scaling
function which has been dilated so that each basis function has a
support equal to 1/8 (=1 pixel) of the support of f which is 8 pixels.
Our goal is to expand f into
in three steps.

. We will do this

Step 1: Expand f into


.
The first step in the example above can be described as the matrixvector multiplication f1=W1f where

(16)

Notice that the first four rows correspond to the basis vectors
and

respectively which span V2.

The last four rows correspond to the basis vectors

and

which span W2.


Hence, the final vector in Step 1 in the example above is nothing
more than the coefficients of f in the expansion
(17)

i.e., we have expanded our signal into

Step 2: Expand f into


.
In this step we notice that we already have the coefficients for the
basis vectors of W2. Hence we don't have to worry about these
coefficients in this step, we simply just keep these coefficients (the

last four entries of our vector in the previous step) and only work
with the first four entries.
The second step can be described as the matrix-vector
multiplication f2=W2f1 where

(18)

We can combine the first and the second step as f2=W2W1f where

(19)

Notice that the first two rows correspond to the basis vectors
and

which span V1.

The third and fourth rows correspond to the basis vectors

and

which span W1. The last four rows correspond to the basis
vectors of W2.
Hence, the final vector in Step 2 in the example above is nothing
else than the coefficients of f in the expansion
(20
)

Step 3: Expand f into


.
In this step we notice that we already have the coefficients for the
basis vectors of
. Hence we don't have to worry about
these coefficients in this step, we simply just keep these
coefficients (the last six entries of our vector in the previous step)
and only work with the first two entries.
The third step can be described as the matrix-vector multiplication
f3=W3f2 where

(21)

We can combine the first, second and third step as f3=W3W2W1f


where

(22
)

Notice that the first row corresponds to the basis vector


spans V0, the second row corresponds to the basis vector
spans W0 and so on.

which
which

Hence, the final vector in Step 3 in the example above is nothing


else than the coefficients of f in the expansion
(23
)

5.3 The wavelet transform as a unitary operator


The procedure in the example above can be expressed as

(24
)
where W is the wavelet transform.
Exercise 4: The wavelet transform as a unitary operator
a) Verify (using, for example, Matlab or Mathematica to reproduce
the example above) that the matrix in (22) describes the wavelet
transform for an 8 dimensional signal.
b) Verify that the wavelet operator in (22) is a unitary operator.
c) Mention a few properties that characterize unitary operators.
5.4 Wavelets and filters
The method of averaging and differencing explained above can
also be expressed as filtering the data. Averaging corresponds to a
low pass filtering. It removes high frequencies of the data. Since
details (sharp changes in the data) correspond to high frequencies,
the averaging procedure tends to smooth the data. The low pass
filter can be expressed as
in the Haar case and when we
average the data, we move this filter along our input data.
The differencing corresponds to high pass filtering. It removes low
frequencies and responds to details of an image since details
correspond to high frequencies. It also responds to noise in an
image, since noise usually is located in the high frequencies. The
high pass filter can be expressed as
in the Haar case and
when we difference the data, we simply move this filter along our
input data. The low pass and high pass filters make up what in
signal processing language is referred to as a filter bank. The
method of averaging and differencing is referred to as analysis.

The reverse procedure (going the opposite way in the example


above) is called synthesis.
Hence, the wavelet transform separates low and high frequencies,
just as the Fourier transform. Since different features of a signal
(background, details, noise, edges, etc.) correspond to different
frequencies, this is a key to use wavelets in signal processing. The
nice thing is that wavelets are localized since they only live on part
of the interval of the data, as opposed to the trigonometric
functions used in Fourier analysis which live on the entire interval
of the data.
6 Exercises
In the previous lab on Fourier techniques in image processing, we
learned that when we want to manipulate an image (compress, denoise, etc.), we first transformed the image into the Fourier basis,
performed our manipulations in this basis, and then transformed
back. The same principle holds when using wavelets techniques for
image processing! Now we will transform our image into a wavelet
basis, perform our manipulations in this basis, and then transform
back. The foundation of signal processing can be described as to
find a basis which is suitable for the manipulations we need. This
means that image processing relies on concepts from linear algebra
such as orthogonality, norms, inner products, etc.
When doing the exercises below, there are a few things you should
keep in mind. Just as you probably has developed a feeling for
what a Fourier spectrum looks like and how it can be interpreted,
try to get a feeling for how a signal looks like in the Haar wavelet
basis. Where can you find the high/low frequencies? Where is the
magnitude of the coefficients large/small?
When you wavelet decompose images, there is a trick to make it
easier to study the decomposition. Usually a major part of the
decomposition (see the image in the beginning of this instruction)

is very dark. If you use Matlab, use the command brighten() to find
a suitable brightness of the picture.
When you run your wavelet transform in Matlab, you may notice
that the transform is quite slow. Even though you may have
implemented your wavelet transform as a ``fast algorithm'', the
architecture of the Matlab language may slow down your
algorithm considerably. This has to do with the fact that loops and
recursive functions calls (which you may need) are time
consuming in Matlab. Don't worry about that, but keep in mind
that your algorithm probably is much faster in C or Fortran which
can handle loops and subroutine calls much more efficient than
Matlab.
Exercise 5: The one dimensional Haar transform
While it is very important to keep in mind that the wavelet
transform can be described by a unitary matrix, it is not efficient to
perform the transformation by multiplying the matrix to a vector.
The way to wavelet transform numerically, is to proceed as in the
example in section 5.2.1 by moving the filters

and

along the signal recursively.


Program a function with the following in-/output:
Input:

A vector of length 2k where k is a positive integer.


The ``level'' of decomposition. (E.g., the first step in the
example in section 5.2.1 corresponds to a first level
decomposition, the second step corresponds to a second level
decomposition and the third step corresponds to a third level
decomposition.)

Output:

A vector which is the Haar transformation of the vector you


gave as input corresponding to the level you gave as an input.

The purpose of this exercise is to build a Haar transform to use for


the following exercises. If you want to use slightly different
input/outputs, feel free to do so as long as you can use your Haar
transform efficiently.
a) Verify that your transform can reproduce the example in section
5.2.1.
b) Verify that the l2-norm is preserved in each of the three steps in
the example.
c) Build an inverse Haar transform, i.e., a code that takes a Haar
transformed vector and returns a non-transformed vector. (A
``reverse'' of the code in a).)
Exercise 6: Compression of a one dimensional signal
Generate a signal that samples the function
(25)

at at least 1024 points. Plot the wavelet decomposition of the signal


at a few different levels.
By using thresholding (like in the previous lab) on the Haar
transformed signal, investigate the compression performance of the
Haar transform. Compare the compression performance to a
compression using the FFT of the same signal.

Bonus question: If this signal represents a sound signal, what does


the signal sound like?
Exercise 7: The two dimensional Haar transform
A standard decomposition of a two dimensional signal (image) is
easily done by first performing a one dimensional transformation
on each row followed by a one dimensional transformation of each
column.
Construct a function that Haar transforms an image for different
levels. Test your function on the same images as used for the
previous labs (the basket and the image with campus and the
Rockies). Compress the image and investigate the compression
performance of the Haar transform compared to using the FFT.
(Hint. The image in the beginning of this lab instruction illustrates
a level 2 Haar transformation of an image. The structure of your
second level Haar transform should look like this one.)
Exercise 8: De-noising images
Using the Haar transform, try to de-noise the following image:

Fractal from Carlson's Fractal Gallery with random noise


added.
(Do not expect your de-noising to do miracles. There are many
approaches to de-noise. The simplest is probably to do
thresholding on your wavelet decomposed image but you may
come up with other methods that work better.)
Exercise 9: Horizontal, vertical and diagonal features
Down load the following image:

Do a Haar wavelet decomposition of this image at a few different


levels. What are your observations? (You may have to adjust the
brightness of the wavelet decomposition using brighten() in
Matlab.)
Exercise 10: ``De-scratching''
Remove (or reduce) the ``scratch'' from the following image!

An MRI (Magnetic Resonance


Imaging) image from First
Radiology Clinic with "a
scratch" added. Medical imaging
is a very important application of
digital image processing.

7 Format of your lab report


Write down your comments to all of the exercises above (word
processed). Include a representative collection of the code(s) that
you used as an appendix. Make sure to include comments in your
code explaining what it does. Include any plots or images you need
to justify your conclusions.
8 Questions?
In case you have questions regarding the material in this lab, do
not hesitate to contact me at kristian.sandberg@colorado.edu or
visit me during my lab hours Mondays 4:30-6 pm and Thursdays
4-5:30 pm in ECCR 143.
Lycka till!

About this document ...


The Haar wavelet transform
This document was generated using the LaTeX2HTML translator
Version 98.1 release (February 19th, 1998)
Copyright 1993, 1994, 1995, 1996, 1997, Nikos Drakos,
Computer Based Learning Unit, University of Leeds.
The command line arguments were:
latex2html -split 0 -no_navigation haar.tex.
The translation was initiated by Kristian Sandberg on 2000-04-01

Kristian Sandberg
2000-04-01

2-D Haar Wavelets


This numerical tour explores 2-D multiresolution analysis with the
Haar transform. It was introduced in 1910 by Haar [Haar1910] and
is arguably the first example of wavelet basis.
Contents

Installing toolboxes and setting up the path.


Forward 2-D Haar transform
Inverse 2-D Haar transform.
Haar Linear Approximation
Haar Non-linear Approximation
Bibliography

Installing toolboxes and setting up the path.


You need to download the following files: signal toolbox and
general toolbox.
You need to unzip these toolboxes in your working directory, so
that you have toolbox_signal and toolbox_general in your
directory.
For Scilab user: you must replace the Matlab comment '%' by its
Scilab counterpart '//'.
Recommandation: You should create a text file named for
instance numericaltour.sce (in Scilab) or numericaltour.m (in
Matlab) to write all the Scilab/Matlab command you want to
execute. Then, simply run exec('numericaltour.sce'); (in Scilab) or
numericaltour; (in Matlab) to run the commands.
Execute this line only if you are using Matlab.
getd = @(p)path(p,path); % scilab users must *not* execute this

Then you can add the toolboxes to the path.


getd('toolbox_signal/');
getd('toolbox_general/');
Forward 2-D Haar transform
The Haar transform is the simplest orthogonal wavelet transform.
It is computed by iterating difference and averaging between odd
and even samples of the signal. Since we are in 2-D, we need to
compute the average and difference in the horizontal and then in
the vertical direction (or in the reverse order, it does not mind).
Size of the image.
n = 256;
N = n*n;
First we load an image.
name = 'hibiscus';
f = load_image(name,n);
f = rescale( sum(f,3) );
The Haar transform operates over scales. It computes a series of
coarse scale and fine scale coefficients where .
J = log2(n)-1;
The forward Haar transform computes
Note that the set of coarse scale coefficients are not stored.
This transform is orthogonal, meaning , and that there is the
following conservation of energy
One initilizes the algorithm with .

The first step apply a vertical transformtion, which corresponds to


applying a 1-D Haar transform on each column, i.e. it computes
from as, for all and ,
Shortcut to compute from .
haarV = @(a)[ a(1:2:length(a),:) + a(2:2:length(a),:);
a(1:2:length(a),:) - a(2:2:length(a),:) ]/sqrt(2);
Display the result of the vertical transform.
clf;
imageplot(f,'Original image',1,2,1);
imageplot(haarV(f),'Vertical transform',1,2,2);

One then apply the same 1-D horizontal transform to both to obtain
the resulting matrices at scale , i.e. to compute as, for all ,
Shortcut for the vertical transform.
haarH = @(a)haarV(a')';
Shortcut for one step of Haar transform.
haar = @(a)haarH(haarV(a));
Display the result of the first step of the algorithm.

clf;
imageplot(f,'Original image',1,2,1);
subplot(1,2,2);
plot_wavelet(haar(f),log2(n)-1); title('Transformed');

The output of the forward transform is stored in the variable fw. At


a given iteration indexed by a scale j, it will store in
fw(1:2^(j+1),1:2^(j+1)) the variable .
Initializes the algorithm at scale .
j = J;
Initialize fw to the full signal.
fw = f;
At iteration indexed by , select the sub-part of the signal containing
, and apply it the Haar operator.

fw(1:2^(j+1),1:2^(j+1)) = haar(fw(1:2^(j+1),1:2^(j+1)));
Exercice 1: (the solution is exo1.m) Implement a full wavelet
transform that extract iteratively wavelet coefficients, by repeating
these steps. Take care of choosing the correct number of steps.
exo1;

Check that the transform is orthogonal, which means that the


energy of the coefficient is the same as the energy of the signal.
fprintf('Should be 0: %.3f.\n', (norm(f(:))-norm(fw(:)))/norm(f(:)));
Should be 0: 0.000.
Display the wavelet coefficients.
clf;
subplot(1,2,1);
imageplot(f); title('Original');

subplot(1,2,2);
plot_wavelet(fw, 1); title('Transformed');

Inverse 2-D Haar transform.


The backward transform computes a signal from a set of
coefficients
If are the coefficients of an image , one recovers .
The inverse transform starts from , and computes from the
knowledge of by first inverting the horizontal transform, for all ,
ihaarV = @(a,d)assign( zeros(2*size(a,1),size(a,2)), ...
[1:2:2*size(a,1), 2:2:2*size(a,1)], [a+d; a-d]/sqrt(2), 1 );
Then one invert the vertical transform, for all and for all
ihaarH = @(a,d)ihaarV(a',d')';

Shortcut to invert horizontal and then vertical transforms. This


defines the invert of the Haar transform.
ihaar = @(a,dH,dV,dD)ihaarV( ihaarH(a,dH), ihaarH(dV,dD) );
Initialize the signal to recover as the transformed coefficient, and
select the smallest possible scale .
f1 = fw;
j = 0;
Apply one step of inverse transform.
s = 1:2^j; t = 2^j+1:2^(j+1); u = 1:2^(j+1);
f1(u,u) = ihaar(f1(s,s),f1(s,t),f1(t,s),f1(t,t));
Exercice 2: (the solution is exo2.m) Write the inverse wavelet
transform that computes from coefficients fW.
exo2;

Check that we recover exactly the original image.


fprintf('Should be 0: %.3f.\n', (norm(f-f1))/norm(f));
Should be 0: 0.000.
Haar Linear Approximation
Linear approximation is obtained by setting to zeros the Haar
coefficient coefficients above a certain scale .
Cut-off scale.
j = J-1;
Set to zero fine scale coefficients.
fw1 = zeros(n); fw1(1:2^j,1:2^j) = fw(1:2^j,1:2^j);

Computing the signal corresponding to these coefficients fw1


computes the orthogonal projection on the space of images that are
constant on disjoint squares of length .
Exercice 3: (the solution is exo3.m) Display the reconstructed
signal obtained from fw1, for a decreasing cut-off scale .
exo3;

Haar Non-linear Approximation


Non-linear approximation is obtained by thresholding low
amplitude wavelet coefficients. It is defined as
where is the hard tresholding operator
S = @(x,T) x .* (abs(x)>T);
Set the threshold value.

T = .1;
Threshold the coefficients.
fwT = S(fw,T);
Display the coefficients before and after thresholding.
clf;
subplot(1,2,1);
plot_wavelet(fw); axis('tight'); title('Original coefficients');
subplot(1,2,2);
plot_wavelet(fwT); axis('tight'); title('Thresholded coefficients');

Exercice 4: (the solution is exo4.m) Find the threshold so that the


number of remaining coefficients in fwT is a fixed number . Use
this threshold to compute fwT and then display the corresponding
approximation of . Try for an increasing number of coeffiients.

exo4;

Bibliography

[Haar1910] Haar A. Zur Theorie der orthogonalen


Funktionensysteme, Mathematische Annalen, 69, pp 331-371,
1910.

Copyright (c) 2010 Gabriel Peyre

Crazy Programmers

Mosaic
Classic
Flipcard
Magazine
Mosaic
Sidebar
Snapshot
Timeslide

Home

MATLAB

Message display program in clanguage using putc(),stdout(),stdin()


Streams
#include
main()
{
char ch[]="Programing is fun";
int k=0;
while(ch[k])
putc(ch[k++],stdout);
}

#include
main(void)
{
char ch[11];
int i;
printf("Input a Text");
for(i=0;i<11;i++)
ch[i]=getc(stdin);
printf("\n The Text inputed was");
for(i=0;i<11;i++)
putc(ch[i],st
Oct
6
Message display program in clanguage using
putc(),stdout(),stdin() Streams
#include<stdio.h>
main()
{
char ch[]="Programing is fun";
int k=0;
while(ch[k])

putc(ch[k++],stdout);
}
#include<stdio.h>
main(void)
{
char ch[11];
int i;
printf("Input a Text");
for(i=0;i<11;i++)
ch[i]=getc(stdin);
printf("\n The Text inputed was");
for(i=0;i<11;i++)
putc(ch[i],stdout);
}
Posted 6th October by Balaramakrishna rachumallu
0
Add a comment
Add commentNo more comments
Program to check the number for Palindrome using C language
#include
#include
main()
{
int n,t,s=0,r;
printf("\n Enter any number");

scanf("%d",&n);
t=n;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n=n/10;
}
if(t==s)
printf("%d is a palindrome number",t);
else
printf("%d is a not palindrome number",t);
getch();
}
Guess The output of program
#include
main()
{

int a=10;
printf("\n %d %d",++a,a++);
getch();
}
Observation: The printf statement get executed from the right side.
Armstrong number program using C language
Armstrong number: A number is called armstrong number when
the sum of quebs of individual digits of a number is equal to the
number itself. To write the program we need to seperate the
individual digits we can do this by first modular division and
division by 10.
Asterisks Graph program using C language
#include
main()
{
int i,j,r;
printf("\n Enter number of rows");
scanf("%d",&r);
for(i=0;i<R;I++)
{
for(j=0;j<I+1;J++)
{

printf("* \t");
}
printf("\n");
}
getch();
}
Perfect number Program using C language
#include
main()
{
int n,i=1,s=0;
printf("\n Enter the number");
scanf("%d",&n);
do
{
if(n%i==0)
{
s=s+i;

}
i++;
if(s>n)
break;
}while(i<N);
if(s==n)
printf("\n %d is perfect number",n);
else
printf("\n %d is not perfect number",n);
getch();
}
Swaping of two integers without another variable
#include
main()
{
int a,b;
printf("\n Enter any two numbers to swap");
scanf("%d %d",&a,&b);
printf("\n Before swaping two numbers are a=%d and b=%d",a,b);

a=a+b;
b=a-b;
a=a-b;
printf("\n After swaping two numbers are a=%d and b=%d",a,b);
getch();
}
Fibonacci Series using C language
The fibonacci series is like 0,1,1,2,3,5,8,13,24,55,89......We can get
this like first two are 0 and 1 from third number on wards we have
to add the previous two numbers for example to get the 5th number
in the series we need to add 3rd and 4th numbers in the series.
Floyd's Triangle using C language
#include
main()
{
int r,p,a=1,i,j;
printf("\n Enter number of rows");
scanf("%d",&r);
for(i=0;i<R;I++)
{
for(j=0;j<I+1;J++)

{
printf("%d \t",a);
a++;
}
printf("\n");
}
getch();
}
Reverse Diagonal Elements of a Square Matrix using C language
Genaerally 3x3 matrix is represented as
| a1 a2 a3|
| a4 a5 a6|
| a7 a8 a9|
We need reverse diagonal elements means a3,a5,a7. Now observe
the indices of these elements they are (0,2),(1,1),(2,0).
String overlaping program using 8086
ASSUME CS:CODE, DS:DATA, ES:data
DATA

SEGMeNT

ORG 8000H
STRING1 DB 'balarama krishna'

string2 db 'rachumallu'
data ends
CODE

SEGMeNT

START: MOV AX, DATA


MOV DS, AX
MOV ES, AX
lea SI, string1
lea DI, string2
MOV CX, 10
add
String transfer in reverse direction using 8086
ASSUME CS:CODE, DS:DATA, ES:data
DATA

SEGMeNT

ORG 8000H
STRING1 DB 'balaram'
LENGTH_STRING1 EQU $-STRING1
data ends
EXTRA SEGMENT

ORG 9000H
STRING2 DB 50D DUP(0H)
EXTRA ENDS
CODE

SEGMENT

START: MOV AX, DATA


MOV DS, AX
MOV AX, EXTRA
MOV ES, AX
String transefer in forward direction using 8086
ASSUME CS:CODE, DS:DATA, ES:EXTRA
DATA

SEGMeNT

ORG 8000H
STRING1 DB 'AKASH'
LENGTH_STRING1 EQU $-STRING1
data ends
EXTRA SEGMENT
ORG 9000H
STRING2 DB 50D DUP(0H)
EXTRA ENDS

CODE

SEGMENT

START: MOV AX, DATA


MOV DS, AX
MOV AX, EXTRA
MOV ES, AX
Sorting numbers in ascending oreder (signed) using 8086 in
assembly language
assume cs:code,ds:data
data segment
org 2000h
series db 81h,82h,93h,95h,10h,56h,33h,99h,13h,44h
count dw 10d
data ends
code segment
start:mov ax,data
mov ds,ax
mov dx,count
dec dx
go:mov cx,dx

lea si,series
nxt_byte:mov al,[si]
cmp al,[si+1]
jl next
xchg al,[si+1]
xchg al,[si]
next
Companding of signal using MULAW in MATLAB
clear all
close all
clc
M=input('enter the signal') %enter the signal with time like
sin(2*pi*[0:0.01:1]
Mmax=max(M)
Mn=M/Mmax
u=input('enter the u value') %default value is 255
Vn=log(1+u*Mn)/(log(1+u))
figure(1)
plot(Mn)

figure(2)
plot(Vn)
figure(3)
plot(Mn,Vn)
ASK Modulation & Demodulation using MATLAB
Base band signal generation Using Matlab
a=input('enter the sequence')
k=length(a)
t=[0.01:0.01:k]
for i=1:1:k
m((i-1)*100+1:i*100)=a(i)
end
plot(m)
xlabel('time')
ylabel('amplitude')
title('base band signal')
Hybrid Shft Keying PSK & FSK using MATLAB
Procedure to work with Topview Simulator to execute programs in
microcontroller 89c51/8051
Open text editor and type the program(preferred
notepad++/notepad) Save it with an extension .asm Open top
view simulatorselect your device name from drop down listselect

the memoryselect the crystal frequencyGo to File-----> load file


and select the program.asm you saved earlierCompile the progra
Steps to execute the Programs on 8086
you need TASM, tlink ,td files to assemble link and create object
and exe files for your program. after getting these files create a
folder in c drive and name it as bin.
Amplitude Shift Keying demodulation Using Multisim
Program to sort numbers in descending order using 8086 (signed
numbers)
assume cs:code,ds:data
data segment
org 2000h
series db 81h,82h,93h,95h,10h,56h,33h,99h,13h,44h
count dw 10d
data ends
code segment
start:mov ax,data
mov ds,ax
mov dx,count
dec dx
go:mov cx,dx
lea si,series

nxt_byte:mov al,[si]
cmp al,[si+1]
jnl next
xchg al,[si+1]
xchg al,[si]
nex
Program to sort numbers in ascending order using 8086 (unsigned
numbers)
assume cs:code,ds:data
data segment
org 2000h
series db 81h,82h,93h,95h,10h,56h,33h,99h,13h,44h
count dw 10d
data ends
code segment
start:mov ax,data
mov ds,ax
mov dx,count
dec dx

go:mov cx,dx
lea si,series
nxt_byte:mov al,[si]
cmp al,[si+1]
jb next
xchg al,[si+1]
xchg al,[si]
next
Program to find the number of numbers having 5th bit as one in a
series using 8086
assume cs:code,ds:data
data segment
org 2000h
series db 56h,32h,45h,11h,32h,87h,97h,65h,55h,88h
numcount db 00h
data ends
code segment
start:mov ax,data
mov ds,ax

mov si,2000
mov cx,0ah
go:mov ax,[si]
test ax,10h
jz next
inc numcount
next:inc si
dec cx
jnz go
mov ah,4ch
int 21h
c
Different types of SIGNALING Schemes using MATLAB
clc
clear all
close all
n=input('enter the number of bits')
m=mod(randperm(n),2)
t=['the binary data is

%binary data
',num2str(m)]

c=input('enter your choice 1.unipolar nrz 2.polar nrz 3.unipolar rz


4.manchester')
switch c
case 1
for i=1:1:n
s((i-1)*100+1:i*100)=m(i)
e
Frequency Shift Keying using MATLAB
Division of two numbers using 8086 in assembly language
assume cs:code,ds:data
data segment
org 2000h
num1 dw 8345h
num2 dw 2346h
rem dw 2d dup(0h)
quo dw 2d dup(0h)
data ends
code segment
start:mov ax,data

mov ds,ax
mov ax,num1
idiv num2
mov quo,ax
mov rem,dx
mov ah,4ch
int 21h
code ends
end start
Finding the product of two numbers using 8086 program in
assembly language
assume cs:code,ds:data
data segment
org 2000h
num1 dw 1234h
num2 dw 2345h
product dw 2d dup(0h)
data ends
code segment

start:mov ax,data
mov ds,ax
mov ax,num1
mul num2
mov product,ax
mov product+2,dx
mov ah,4ch
int 21h
code ends
end start
finding the sum of two numbers using 8086 in assembly language
assume cs:code,ds:data
data segment
org 2000h
num1 dw 1234h
num2 dw 2345h
sum db 2d dup(0h)
carry db 1d dup(0h)
data ends

code segment
start:mov ax,data
mov ds,ax
mov ax,num1
mov bx,num2
add al,bl
daa
mov sum,al
mov al,ah
adc al,bh
daa
mov sum+1,al
mov bl,0h
adc bl,0h
mov carry
Assembly language program to find the sum of numbers in a given
series using 8086
assume cs:code,ds:data
data segment

org 2000h
series dw 1234h,2345h,0abcdh,103fh,5555h
sum dw 00h
carry dw 00h
data ends
code segment
start:mov ax,data
mov ds,ax
mov ax,00h
mov bx,00h
mov cx,05h
mov si,2000h
go:add ax,[si]
adc bx,00h
inc si
inc si
dec cx

jnz go
mov sum,ax
mov ca
Assembly language program to find the number of ones in a given
number using 8086
assume cs:code,ds:data
data segment
org 2000h
num dw 4567h
onecount db 01d dup(0h)
data ends
code segment
start:mov ax,data
mov ds,ax
mov cx,16d
mov ax,num
go:ror ax,01
jnc next
inc onecount

next:dec cx
jnz go
mov ah,4ch
int 21h
code ends
end start
Assembly language program to find maximum and minimum
number in a series using 8086
assume cs:code,ds:data
data segment
org 2000h
series db 12h,11h,09h,05h,23h,99h,86h
count dw 07h
max db 00h
min db 00h
data ends
code segment
start:mov ax,data
mov ds,ax

mov cx,count
lea si,series
mov al,[si]
mov bl,al
go:inc si
cmp [si],al
jl min_val
mov al,[si]
jmp nxtp
min_val
Assembly language program to convert binary number to BCD
using 8086 using procedures
ASSUME CS:CODE, DS:DATA, SS:STACK1
DATA

SEGMENT

SERIES DB 74H,29H,4AH,3BH
BCD_OUT DW 04H DUP(0H)
BCD
DATA

EQU 04H
ENDS

STACK1 SEGMENT

BALARAM DW 40H DUP(0H)


TOP_STACK LABEL WORD
STACK1 ENDS
CODE SEGMENT
START: MOV AX, DATA
MOV DS, AX
MOV AX, STACK1
Display string on scrren in assembly language using 8086
assume cs:code,ds:data
data segment
org 2000h
msg db "MICROPROCESSORLAB",0DH,0AH,"$"
data ends
code segment
start:
mov ax,data
mov ds,ax
lea dx,msg
mov ah,09h

int 21h
mov ah,4ch
int 21h
code ends
end start
Find the string for polindrome or not using 8086 program in
assembly language
assume cs:code,ds:data,es:data
data segment
org 2000h
msg1 db "enter your string",0dh,0ah,"$"
msg2 db "It is palindrom",0dh,0ah,"$"
msg3 db "It is not palindrom",0dh,0ah,"$"
msg4 db "Do you wish to continue y/n",0dh,0ah,"$"
org 4000h
strg1 db 50h dup(0h)
org 6000h
strg2 db 50h dup(
Find the factorial of a given number using 8086 program in
assembly language

ASSUME CS:CODE, DS:DATA, SS:STACK1


DATA SEGMENT
NUM DW 05H
FACT DW 0H
DATA ENDS
STACK1 SEGMENT
STK DW 100H DUP(0H)
TOP_STACK LABEL WORD
STACK1 ENDS
CODE SEGMENT
START: MOV AX, DATA
MOV DS, AX
MOV AX, STACK1
MOV SS, AX
LEA SP, TOP_STACK
MOV AX,
Finding the number of even and odd numbers in a given series in
assembly language using 8086
ASSUME CS:CODE, DS:DATA

DATA

SEGMENT

ORG 5000H
SERIES DB 35H,66H,11H,12H,22H,56H,8H,2H,1H,9H
COUNT DB 0AH
ODDCOUNT DB 00H
EVENCOUNT DB 00H
DATA

ENDS

CODE

SEGMENT

START: MOV AX, DATA


MOV DS, AX
LEA SI, SERIES
MOV CL, COUNT
NEXT: MOV AX, [SI
Data transfer in reverse direction in assembly language in 8086
assume cs:code,ds:data
data segment
org 2000h
array1 db 01h,02h,03h,04h,05h,06h,07h,08h,09h,0ah
org 4000h

array2 db 10d dup(0h)


data ends
code segment
start:mov ax,data
mov ds,ax
mov si,2000h
mov di,4009h
mov cx,10d
go:mov al,[si]
mov [di],al
inc si
dec di
dec cx
jnz go
mov ah,4ch
Addition of two numbers in assembly language using 8086
ASSUME CS:CODE, DS:DATA
DATA

SEGMENT

ORG 3000H
NUM1 DB 22H
NUM2 DB 32H
SUM DB 00H
DATA

ENDS

CODE

SEGMENT

ASSUME CS:CODE, DS:DATA


START: MOV AX, DATA
MOV DS, AX
MOV AL, NUM1
MOV BL, NUM2
ADD AL, BL
Data transfer in forward direction in assembly language using 8086
assume cs:code,ds:data
data segment
org 2000h
array1 db 01h,02h,03h,04h,05h,06h,07h,08h,09h,0ah
org 4000h
array2 db 50d dup(0h)

data ends
code segment
start:mov ax,data
mov ds,ax
mov si,2000h
mov di,4000h
mov cx,10d
go:mov al,[si]
mov [di],al
inc si
inc di
dec cx
jnz go
mov ah,4ch

Blog Archive

Subscribe

Loading

Send feedback

Crazy Programmers
Mosaic
Classic
Flipcard
Magazine
Mosaic
Sidebar
Snapshot
Timeslide

Home

MATLAB

Message display program in clanguage using putc(),stdout(),stdin()


Streams

#include
main()
{
char ch[]="Programing is fun";
int k=0;
while(ch[k])
putc(ch[k++],stdout);
}
#include
main(void)
{
char ch[11];
int i;
printf("Input a Text");
for(i=0;i<11;i++)
ch[i]=getc(stdin);
printf("\n The Text inputed was");
for(i=0;i<11;i++)

putc(ch[i],st
Program to check the number for Palindrome using C language
#include
#include
main()
{
int n,t,s=0,r;
printf("\n Enter any number");
scanf("%d",&n);
t=n;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n=n/10;
}
if(t==s)
printf("%d is a palindrome number",t);

else
printf("%d is a not palindrome number",t);
getch();
}
Guess The output of program
#include
main()
{
int a=10;
printf("\n %d %d",++a,a++);
getch();
}
Observation: The printf statement get executed from the right side.
Armstrong number program using C language
Armstrong number: A number is called armstrong number when
the sum of quebs of individual digits of a number is equal to the
number itself. To write the program we need to seperate the
individual digits we can do this by first modular division and
division by 10.
Asterisks Graph program using C language
#include
main()
{

int i,j,r;
printf("\n Enter number of rows");
scanf("%d",&r);
for(i=0;i<R;I++)
{
for(j=0;j<I+1;J++)
{
printf("* \t");
}
printf("\n");
}
getch();
}
Perfect number Program using C language
#include
main()
{
int n,i=1,s=0;

printf("\n Enter the number");


scanf("%d",&n);
do
{
if(n%i==0)
{
s=s+i;
}
i++;
if(s>n)
break;
}while(i<N);
if(s==n)
printf("\n %d is perfect number",n);
else
printf("\n %d is not perfect number",n);
getch();
}

Swaping of two integers without another variable


#include
main()
{
int a,b;
printf("\n Enter any two numbers to swap");
scanf("%d %d",&a,&b);
printf("\n Before swaping two numbers are a=%d and b=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\n After swaping two numbers are a=%d and b=%d",a,b);
getch();
}
Fibonacci Series using C language
The fibonacci series is like 0,1,1,2,3,5,8,13,24,55,89......We can get
this like first two are 0 and 1 from third number on wards we have
to add the previous two numbers for example to get the 5th number
in the series we need to add 3rd and 4th numbers in the series.
Floyd's Triangle using C language
#include
main()

{
int r,p,a=1,i,j;
printf("\n Enter number of rows");
scanf("%d",&r);
for(i=0;i<R;I++)
{
for(j=0;j<I+1;J++)
{
printf("%d \t",a);
a++;
}
printf("\n");
}
getch();
}
Reverse Diagonal Elements of a Square Matrix using C language
Genaerally 3x3 matrix is represented as
| a1 a2 a3|

| a4 a5 a6|
| a7 a8 a9|
We need reverse diagonal elements means a3,a5,a7. Now observe
the indices of these elements they are (0,2),(1,1),(2,0).
String overlaping program using 8086
ASSUME CS:CODE, DS:DATA, ES:data
DATA

SEGMeNT

ORG 8000H
STRING1 DB 'balarama krishna'
string2 db 'rachumallu'
data ends
CODE

SEGMeNT

START: MOV AX, DATA


MOV DS, AX
MOV ES, AX
lea SI, string1
lea DI, string2
MOV CX, 10
add
String transfer in reverse direction using 8086

ASSUME CS:CODE, DS:DATA, ES:data


DATA

SEGMeNT

ORG 8000H
STRING1 DB 'balaram'
LENGTH_STRING1 EQU $-STRING1
data ends
EXTRA SEGMENT
ORG 9000H
STRING2 DB 50D DUP(0H)
EXTRA ENDS
CODE

SEGMENT

START: MOV AX, DATA


MOV DS, AX
MOV AX, EXTRA
MOV ES, AX
String transefer in forward direction using 8086
ASSUME CS:CODE, DS:DATA, ES:EXTRA
DATA

SEGMeNT

ORG 8000H

STRING1 DB 'AKASH'
LENGTH_STRING1 EQU $-STRING1
data ends
EXTRA SEGMENT
ORG 9000H
STRING2 DB 50D DUP(0H)
EXTRA ENDS
CODE

SEGMENT

START: MOV AX, DATA


MOV DS, AX
MOV AX, EXTRA
MOV ES, AX
Sorting numbers in ascending oreder (signed) using 8086 in
assembly language
assume cs:code,ds:data
data segment
org 2000h
series db 81h,82h,93h,95h,10h,56h,33h,99h,13h,44h
count dw 10d

data ends
code segment
start:mov ax,data
mov ds,ax
mov dx,count
dec dx
go:mov cx,dx
lea si,series
nxt_byte:mov al,[si]
cmp al,[si+1]
jl next
xchg al,[si+1]
xchg al,[si]
next
Companding of signal using MULAW in MATLAB
clear all
close all
clc

M=input('enter the signal') %enter the signal with time like


sin(2*pi*[0:0.01:1]
Mmax=max(M)
Mn=M/Mmax
u=input('enter the u value') %default value is 255
Vn=log(1+u*Mn)/(log(1+u))
figure(1)
plot(Mn)
figure(2)
plot(Vn)
figure(3)
plot(Mn,Vn)
ASK Modulation & Demodulation using MATLAB
Apr
13
ASK Modulation & Demodulation using MATLAB
Amplitude Shift Keying:
Amplitude shift keying (ASK) is a very popular modulation
used in control applications. This is due to its simplicity and low

implementation costs. ASK modulation has the advantage of


allowing the transmitter to idle during the transmission of a bit
zero. Therefore this reduces the power consumption. This
disadvantage of ASK modulation arises in the presence of an
undesired signal. in amplitude shift keying (ASK), as the name
specifies the amplitude of the carrier signal is varied between two
levels if the ASK scheme is Binary ASK. Sometimes it is more
than two levels if the ASK scheme is M-array. All this is done
according to the data bit to be transmitted over the noisy channel.
The information is assumed to be unipolar binary data. In binary
ask bit 1 is transmitted with the carrier of specified amplitude. The
bit zero is transmitted with the no carrier during the bit interval.
During all the bit intervals amplitude will be changed but
frequency will be kept constant. In M-array ask the amplitude
levels of the carrier will change between M numbers of values. The
main advantage of the ASK is power saving and simplicity in
implementation. The ASK wave form can be represented
mathematically as s(t)=m(t)*sin(2f ct). where s(t) is the ASK
output signal, m(t) is the unipolar binary message signal to be
transmitted and fc is the carrier frequency.Amplitude
shift
keying (ASK) is a simple and elementary form of
digital modulation in which the amplitude of a carrier sinusoid is
modified in a discrete manner depending on the value of a
modulating symbol.This is a narrow band modulation scheme and
we assume that a large number carrier cycles are sent within a
symbol interval. obvious that the information is embedded only in
the peak amplitude of the modulated signal.this is described as a
one type of digital amplitude modulation technique. BASK has
only one basis function so this can be described as a one
dimensional modulation scheme.this technique is used for
telegraph services.on-off keying is not a spectrally not efficeint
scheme becuse as the amplitude of the carrier changes abruptly
when the data bit changes. for this reason this technique is used for
transmission of data at low or moderate data rates.

Algorithm:
The binary message to be transmitted is taken and it
should be represented in a waveform so we can implement ask.
Then generate the carrier it may be either sin or cos. After
generating carrier multiply the carrier with the message point by
point.
in demodulation the code checks for the value and if the
value matched during the all the bit interval then the value will be
returned.
Matlab commands:
1.

K=Length(x)
It finds the length of the array x and returns its length as an integer.

2.

T=[0.01:0.01:k]
This specifies the time interval over which the carrier time period
will be decided.

3.

Z=m.*c
This is matlab Command for point by point multiplication.
Sometimes it generates errors if the m and c are not of same
dimensions.
4.
M((i-1)*100+1:i*100)=a(i)
This applies the value of the message bit i during the specified
interval.
5.

p = randperm(n)
Returns a random permutation of the integers 1:n.

6.

mod(1,randperm(n))
this command generates the n number of integers and all these
having only two values. For example mod(1,randperm(5)) ans
=[0 1 1 1 1]

program:
x=input('binary message signal')%binary message signal
l=length(x)%length of message
t=[0.01:0.01:l]%time scaling
c=cos(2*pi*t)%carrier signal
for i=1:1:l
m((i-1)*100+1:i*100)=x(i)%loop to convert inputed sequence to
pulsewave
end
a=c.*m
figure(1)
plot(m)
title('massage signal')
figure(2)
plot(a)
title('ASK Signal')
%%% ASK Demodulation envelope detection without noise%%%
for i=1:1:(i*100)
if a(i)==0
r(i)=0
else
r(i)=1
end
end
figure(3)
plot(r)
title('recovered signal')

Posted 13th April by Balaramakrishna rachumallu


0
Add a comment
Add commentNo more comments
Base band signal generation Using Matlab
a=input('enter the sequence')
k=length(a)
t=[0.01:0.01:k]
for i=1:1:k
m((i-1)*100+1:i*100)=a(i)
end
plot(m)
xlabel('time')

ylabel('amplitude')
title('base band signal')
Hybrid Shft Keying PSK & FSK using MATLAB
Procedure to work with Topview Simulator to execute programs in
microcontroller 89c51/8051
Open text editor and type the program(preferred
notepad++/notepad) Save it with an extension .asm Open top
view simulatorselect your device name from drop down listselect
the memoryselect the crystal frequencyGo to File-----> load file
and select the program.asm you saved earlierCompile the progra
Steps to execute the Programs on 8086
you need TASM, tlink ,td files to assemble link and create object
and exe files for your program. after getting these files create a
folder in c drive and name it as bin.
Amplitude Shift Keying demodulation Using Multisim
Program to sort numbers in descending order using 8086 (signed
numbers)
assume cs:code,ds:data
data segment
org 2000h
series db 81h,82h,93h,95h,10h,56h,33h,99h,13h,44h
count dw 10d
data ends
code segment
start:mov ax,data
mov ds,ax

mov dx,count
dec dx
go:mov cx,dx
lea si,series
nxt_byte:mov al,[si]
cmp al,[si+1]
jnl next
xchg al,[si+1]
xchg al,[si]
nex
Program to sort numbers in ascending order using 8086 (unsigned
numbers)
assume cs:code,ds:data
data segment
org 2000h
series db 81h,82h,93h,95h,10h,56h,33h,99h,13h,44h
count dw 10d
data ends
code segment

start:mov ax,data
mov ds,ax
mov dx,count
dec dx
go:mov cx,dx
lea si,series
nxt_byte:mov al,[si]
cmp al,[si+1]
jb next
xchg al,[si+1]
xchg al,[si]
next
Program to find the number of numbers having 5th bit as one in a
series using 8086
assume cs:code,ds:data
data segment
org 2000h
series db 56h,32h,45h,11h,32h,87h,97h,65h,55h,88h
numcount db 00h

data ends
code segment
start:mov ax,data
mov ds,ax
mov si,2000
mov cx,0ah
go:mov ax,[si]
test ax,10h
jz next
inc numcount
next:inc si
dec cx
jnz go
mov ah,4ch
int 21h
c
Different types of SIGNALING Schemes using MATLAB
clc

clear all
close all
n=input('enter the number of bits')
m=mod(randperm(n),2)
t=['the binary data is

%binary data
',num2str(m)]

c=input('enter your choice 1.unipolar nrz 2.polar nrz 3.unipolar rz


4.manchester')
switch c
case 1
for i=1:1:n
s((i-1)*100+1:i*100)=m(i)
e
Frequency Shift Keying using MATLAB
Division of two numbers using 8086 in assembly language
assume cs:code,ds:data
data segment
org 2000h
num1 dw 8345h
num2 dw 2346h
rem dw 2d dup(0h)

quo dw 2d dup(0h)
data ends
code segment
start:mov ax,data
mov ds,ax
mov ax,num1
idiv num2
mov quo,ax
mov rem,dx
mov ah,4ch
int 21h
code ends
end start
Finding the product of two numbers using 8086 program in
assembly language
assume cs:code,ds:data
data segment
org 2000h
num1 dw 1234h

num2 dw 2345h
product dw 2d dup(0h)
data ends
code segment
start:mov ax,data
mov ds,ax
mov ax,num1
mul num2
mov product,ax
mov product+2,dx
mov ah,4ch
int 21h
code ends
end start
finding the sum of two numbers using 8086 in assembly language
assume cs:code,ds:data
data segment
org 2000h

num1 dw 1234h
num2 dw 2345h
sum db 2d dup(0h)
carry db 1d dup(0h)
data ends
code segment
start:mov ax,data
mov ds,ax
mov ax,num1
mov bx,num2
add al,bl
daa
mov sum,al
mov al,ah
adc al,bh
daa
mov sum+1,al
mov bl,0h

adc bl,0h
mov carry
Assembly language program to find the sum of numbers in a given
series using 8086
assume cs:code,ds:data
data segment
org 2000h
series dw 1234h,2345h,0abcdh,103fh,5555h
sum dw 00h
carry dw 00h
data ends
code segment
start:mov ax,data
mov ds,ax
mov ax,00h
mov bx,00h
mov cx,05h
mov si,2000h
go:add ax,[si]

adc bx,00h
inc si
inc si
dec cx
jnz go
mov sum,ax
mov ca
Assembly language program to find the number of ones in a given
number using 8086
assume cs:code,ds:data
data segment
org 2000h
num dw 4567h
onecount db 01d dup(0h)
data ends
code segment
start:mov ax,data
mov ds,ax
mov cx,16d

mov ax,num
go:ror ax,01
jnc next
inc onecount
next:dec cx
jnz go
mov ah,4ch
int 21h
code ends
end start
Assembly language program to find maximum and minimum
number in a series using 8086
assume cs:code,ds:data
data segment
org 2000h
series db 12h,11h,09h,05h,23h,99h,86h
count dw 07h
max db 00h
min db 00h

data ends
code segment
start:mov ax,data
mov ds,ax
mov cx,count
lea si,series
mov al,[si]
mov bl,al
go:inc si
cmp [si],al
jl min_val
mov al,[si]
jmp nxtp
min_val
Assembly language program to convert binary number to BCD
using 8086 using procedures
ASSUME CS:CODE, DS:DATA, SS:STACK1
DATA

SEGMENT

SERIES DB 74H,29H,4AH,3BH

BCD_OUT DW 04H DUP(0H)


BCD

EQU 04H

DATA

ENDS

STACK1 SEGMENT
BALARAM DW 40H DUP(0H)
TOP_STACK LABEL WORD
STACK1 ENDS
CODE SEGMENT
START: MOV AX, DATA
MOV DS, AX
MOV AX, STACK1
Display string on scrren in assembly language using 8086
assume cs:code,ds:data
data segment
org 2000h
msg db "MICROPROCESSORLAB",0DH,0AH,"$"
data ends
code segment

start:
mov ax,data
mov ds,ax
lea dx,msg
mov ah,09h
int 21h
mov ah,4ch
int 21h
code ends
end start
Find the string for polindrome or not using 8086 program in
assembly language
assume cs:code,ds:data,es:data
data segment
org 2000h
msg1 db "enter your string",0dh,0ah,"$"
msg2 db "It is palindrom",0dh,0ah,"$"
msg3 db "It is not palindrom",0dh,0ah,"$"
msg4 db "Do you wish to continue y/n",0dh,0ah,"$"

org 4000h
strg1 db 50h dup(0h)
org 6000h
strg2 db 50h dup(
Find the factorial of a given number using 8086 program in
assembly language
ASSUME CS:CODE, DS:DATA, SS:STACK1
DATA SEGMENT
NUM DW 05H
FACT DW 0H
DATA ENDS
STACK1 SEGMENT
STK DW 100H DUP(0H)
TOP_STACK LABEL WORD
STACK1 ENDS
CODE SEGMENT
START: MOV AX, DATA
MOV DS, AX
MOV AX, STACK1

MOV SS, AX
LEA SP, TOP_STACK
MOV AX,
Finding the number of even and odd numbers in a given series in
assembly language using 8086
ASSUME CS:CODE, DS:DATA
DATA

SEGMENT

ORG 5000H
SERIES DB 35H,66H,11H,12H,22H,56H,8H,2H,1H,9H
COUNT DB 0AH
ODDCOUNT DB 00H
EVENCOUNT DB 00H
DATA

ENDS

CODE

SEGMENT

START: MOV AX, DATA


MOV DS, AX
LEA SI, SERIES
MOV CL, COUNT
NEXT: MOV AX, [SI
Data transfer in reverse direction in assembly language in 8086

assume cs:code,ds:data
data segment
org 2000h
array1 db 01h,02h,03h,04h,05h,06h,07h,08h,09h,0ah
org 4000h
array2 db 10d dup(0h)
data ends
code segment
start:mov ax,data
mov ds,ax
mov si,2000h
mov di,4009h
mov cx,10d
go:mov al,[si]
mov [di],al
inc si
dec di
dec cx

jnz go
mov ah,4ch
Addition of two numbers in assembly language using 8086
ASSUME CS:CODE, DS:DATA
DATA

SEGMENT

ORG 3000H
NUM1 DB 22H
NUM2 DB 32H
SUM DB 00H
DATA

ENDS

CODE

SEGMENT

ASSUME CS:CODE, DS:DATA


START: MOV AX, DATA
MOV DS, AX
MOV AL, NUM1
MOV BL, NUM2
ADD AL, BL
Data transfer in forward direction in assembly language using 8086
assume cs:code,ds:data

data segment
org 2000h
array1 db 01h,02h,03h,04h,05h,06h,07h,08h,09h,0ah
org 4000h
array2 db 50d dup(0h)
data ends
code segment
start:mov ax,data
mov ds,ax
mov si,2000h
mov di,4000h
mov cx,10d
go:mov al,[si]
mov [di],al
inc si
inc di
dec cx
jnz go

mov ah,4ch
Data Over laping in assembly language using 8086
assume cs:code,ds:data
data segment
org 2000h
array db 01h,02h,03h,04h,05h,06h,07h,08h,09h,0ah
data ends
code segment
start:mov ax,data
mov ds,ax
mov si,2009h
mov di,200eh
mov cx,10d
go:mov al,[si]
mov [di],al
dec si
dec di
dec cx

jnz go
mov ah,4ch
int 21h
code ends
end start
LCD INTERFACING using 8051/89c51 using TOPView
Simulator
2 lines 16 characters, 8 bits, port line selection EN - P3.2,RS P3.1,RW - P3.3
$MOD51
EN EQU P3.2
RS EQU P3.1
RW EQU P3.3
ORG 0000H
MOV A,#38H
LCALL LCD_COMD
MOV A,#0EH
LCALL LCD_COMD
MOV A,#06H
LCALL LCD_COMD

MOV A,#01H
LCALL LCD_COMD
MOV A,#'E'
LCALL LCD_TEXT
MOV A,#'C'
LCALL L
INTERFACING OF 2 DIGIT SEVENSEGMENT DISPLAY
THROUGH 7447 In 89c51/8051 with topview simulator
NOTE: When initializing the external modules set these settings
NON Multiplexed, green or red, common cathode, BCD.
INTERFACE OF LEDS TO GET THE TOGGLE OPERATION in
8051/89c51 in topview simulator
$mod51
mov a,#0aah
repeat: mov p1,a
cpl a
lcall delay
sjmp repeat
delay:mov r2,#0ffh
back:mov r1,#0ffh

up1:nop
nop
djnz r1,up1
djnz r2,back
ret
end
Finding the compliment of numbers using 89c51 microcontroller
and topview simulator
$mod51
Org 0000h
mov dptr,#0100h
movx a,@dptr
cpl a
inc dptr
movx @dptr,a
stop:sjmp stop
end
Division of two numbers using 89c51 microcontroller
$mod51
org 0000h

mov dptr,0100h
movx a,@dptr
inc dptr
movx b, @dptr
div a,b
inc dptr
movx @dptr,a
mov a,b
inc dptr
movx @dptr,a
stop:sjmp stop
end
Multiplication of two numbers using 89c51 microcontroller
$mod51
org 0000h
mov dptr,0100h
movx a,@dptr
inc dptr
movx b, @dptr

mul a,b
inc dptr
movx @dptr,a
mov a,b
inc dptr
movx @dptr,a
stop:sjmp stop
end
Substraction of two numbers using 89c51 microcontroller
$mod51
org 0000h
mov dptr,#0100h
movx a,@dptr
inc dptr
movx b,@dptr
clr c
subb a,b
inc dptr

movx @dptr,a
clr a
addc a,#00h
inc dptr
movx @dptr,a
stop:sjmp stop
end
Addition of two numbers using 89c51 microcontroller
$mod51
org 0000h
mov dptr,#0100h
movx a,@dptr
inc dptr
movx b,@dptr
add a,b
inc dptr
movx @dptr,a
clr a
addc a,#00h

inc dptr
movx @dptr,a
stop:sjmp stop
end
Program to display the entered string on screen using 8086
ASSUME CS:CODE,DS:DATA
DATA

SEGMENT

ORG
INPUT

2000H

DB

OUTPUT
,0DH,0AH,$
S_LENTH

ENTER THE STRING,0DH,0AH,$

DB

THE ENTERED STRING IS:

DB

BUFFER
DB
80
finding the given string as a palindrome or not. using 8086
ASSUME CS:CODE,DS:DATA
DATA SEGMENT
ORG 2000H
STRING
S_LENTH

DB

MPMC LAB$

EQU

MSG1 DB

$-STRING-1

THE GIVEN STRING IS A

PALINDROME$
MSG2 DB THE
Factorial of a given number with macro using 8086
FACTORIAL MACRO
XOR CX,CX
XOR AX,AX
INC AX
MOV CL,NUMBER
CMP CL,0
JE GO
Hexadecimal to BCD conversion using 8086
ASSUME CS:CODE,DS:DATA
DATA

SEGMENT

ORG
HEXA
A_LENTH

2000H

DB

55H, 99H, 77H, 22H

EQU

DECI_NO
DB
Circular Convolution using fft Matlab
x1=input('enter the first sequence')
x2=input('enter the second seqquence')
N1=length(x1)

$-ARRAY

N2=length(x2)
if N1>N2
x2=[x2,zeros(N2-N1)]
two sequences equal

%padding zeros to make lengths of

end
if N2>N1
x1=[x1,zeros(N2-N1)]
end
N=max(N1,N2)
X1=fft(x1,N);
X2=fft(x2,N);
X3=X1.*
Desimation in frequency FFT using Matlab
x=input('enter the sequence')
N=length(x)
s=log2(N)
for m=s-1:-1:0
for p=0:1:((2^m)-1)
for k=p:(2^(m+1)):N-1

b=x(k+1)
t=(exp(-pi*1i*p/(2^m)))
x(k+1)=b+x(k+(2^m)+1)
x(k+(2^m)+1)=(b-x(k+(2^m)+1))*t
end
end
pulsecode modulation using matlab/PCM using Matlab
Delta modulation Using MATLAB
sampling using matlab
clc
clear all
close all
fsm=4000
f=1
t=0:(1/fsm):1
m=sin(2*pi*f*t)
figure(1)
plot(t,m)
subplot(211)

plot(t,m)
subplot(212)
plot(m)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
generating impulse train %%%%%%%%%%%%%%%%
fs=(100*f);
s=sin(2*pi*fs*t);
k=s;
k(k<1)=0;
sam=k;
figure
plot(s);
hold a
pulsecode modulation using matlab
sampling process using matlab
clear all
close all
clf
fb=1000
hetz

%baseband signal freqquency in

tb=1/fb
fs=40000
ns=fs/fb
of the base band signal

%number of samples in one period

t=linspace(0,.002,ns)
sq=(1+square(t))/2
asb=5*sin(2*pi*fb*t).*sq
su
on off keying/amplitude shift keying using matlab

Blog Archive

Subscribe
Send feedback

Loading

Transforms
ztrans
Z-transform
Syntax
ztrans(f,trans_index,eval_point)
Description

ztrans(f,trans_index,eval_point) computes the Z-transform of f


with respect to the transformation index trans_index at the point
eval_point.
Input Arguments
f
Symbolic expression, symbolic function, or
vector or matrix of symbolic expressions or
functions.
trans_index

Symbolic variable representing the


transformation index. This variable is often called
the "discrete time variable".
Default: The variable n. If f does not contain n,
then the default variable is determined by
symvar.

eval_point

Symbolic variable or expression representing the


evaluation point. This variable is often called the
"complex frequency variable".
Default: The variable z. If z is the transformation
index of f, then the default evaluation point is the
variable w.

Examples
Compute the Z-transform of this expression with respect to the
transformation index k at the evaluation point x:
syms k x
f = sin(k);
ztrans(f, k, x)
ans =
(x*sin(1))/(x^2 - 2*cos(1)*x + 1)
Compute the Z-transform of this expression calling the ztrans
function with one argument. If you do not specify the
transformation index, ztrans uses the variable n:
syms a n x
f = a^n;

ztrans(f, x)
ans =
-x/(a - x)
If you also do not specify the evaluation point, ztrans uses the
variable z:
ztrans(f)
ans =
-z/(a - z)
Compute the following Z-transforms that involve the Heaviside
function and the binomial coefficient:
syms n z
ztrans(heaviside(n - 3), n, z)
ans =
(1/(z - 1) + 1/2)/z^3
ztrans(nchoosek(n, 2)*heaviside(5 - n), n, z)
ans =
z/(z - 1)^3 + 5/z^5 + (6*z - z^6/(z - 1)^3 + 3*z^2 + z^3)/z^5
If ztrans cannot find an explicit representation of the transform, it
returns an unevaluated call:
syms f(n) z
F = ztrans(f, n, z)
F(z) =
ztrans(f(n), n, z)
iztrans returns the original expression:
iztrans(F, z, n)
ans(n) =
f(n)
More About
expand all
Z-Transform
The Z-transform of the expression f = f(n) is defined as follows:

Tips
If you call ztrans with two arguments, it assumes that the second
argument is the evaluation point eval_point.
If f is a matrix, ztrans applies the Z-transform to all components of
the matrix.
To compute the inverse Z-transform, use iztrans.
Compute Z-Transforms and Inverse Z-Transforms
See Also
fourier | ifourier | ilaplace | iztrans | laplace
Was this topic helpful?
Acknowledgments
Trademarks
Patents
Terms of Use
1994-2012 The MathWorks, Inc.
Try MATLAB, Simulink, and Other Products
Matlab for Laplace Transform Inversion / Partial Fraction
Expansion
Contents

Background: Matlab and polynomials


First Example - Simplest case - distinct real roots
Second Example - Repeated roots at origin
Third Example - Complex Conjugate roots
Fourth Example - Order of numerator=order of denominator

The code that generated this page is available at:


http://lpsa.swarthmore.edu/LaplaceXform/InvLaplace/PFE1Matlab
/PFE1.m

Background: Matlab and polynomials


Define the polynomial
F=[1 3 2]
F=
1

Display it
poly2str(F,'s')
ans =
s^2 + 3 s + 2
Evaluate it as s=1
polyval(F,1)
ans =
6
Find roots, Note that since roots are at -1 and -2 the polynomial is
(s+1)(s+2)
roots(F)
ans =
-2
-1

Define a second polynomial by its roots The polynomial is


G=poly([-1+2j -1-2j -1 0 0]);
poly2str(G,'s')
ans =
s^5 + 3 s^4 + 7 s^3 + 5 s^2
Multiply polynomials H=FG (use convolution command)
H=conv(F,G)
H=
1

18

32

29

10

First Example - Simplest case - distinct real roots


To see this example worked out manually go to:
http://lpsa.swarthmore.edu/LaplaceXform/InvLaplace/InvLaplace
XformPFE.html#Distinct_Real_Roots_
disp('Example 1: PFE with distinct real roots');
Example 1: PFE with distinct real roots
This case considers only distinct real roots.

Define numerator and denominator polynomial.


n=[1 1];
%n=s+1
d=conv([1 0],[1 2]); %Use "conv" to multiply polynomial
disp(['Numerator = ' poly2str(n,'s')]);

disp(['Denominator = ' poly2str(d,'s')]);


Numerator = s + 1
Denominator = s^2 + 2 s
Now use "residue" command to do inverse transform. r =
magnitude of expansion term p = location of pole of each term k =
constnat term (k=0 except when numerator and denominator are
same order (m=n)).
[r,p,k]=residue(n,d)
r=
0.5000
0.5000
p=
-2
0
k=
[]

Note that the function is implicitly defined only for t>=0. Some
texts show the time domain function multiplied by the unit step.
We will keep our expressions simpler by making that relationship
implicit.

Second Example - Repeated roots at origin


To see this example worked out manually go to:
http://lpsa.swarthmore.edu/LaplaceXform/InvLaplace/InvLaplace
XformPFE.html#Repeated_Real_Roots_
disp('Example 2: PFE with repeated real roots (at origin in this
case)');
Example 2: PFE with repeated real roots (at origin in this case)

Define numerator and denominator polynomial.


n=[1 0 1]; %n=s^2+1
d=[1 2 0 0]; %d=s^2(s+2)=s^3+2s^2
disp(['Numerator = ' poly2str(n,'s')]);
disp(['Denominator = ' poly2str(d,'s')]);
[r,p,k]=residue(n,d)
Numerator = s^2 + 1
Denominator = s^3 + 2 s^2
r=
1.2500
-0.2500
0.5000
p=
-2
0

0
k=
[]
Note, first order term (1/s) comes before the 2nd order term (1/s^2)
in the Matlab results.

Third Example - Complex Conjugate roots


To see this example worked out manually go to:
http://lpsa.swarthmore.edu/LaplaceXform/InvLaplace/InvLaplace
XformPFE.html#ExampleRepeat
disp('Example 3: PFE with complex conjugate roots.');
Example 3: PFE with complex conjugate roots.

Define numerator and denominator polynomial.


n=[5 8 -5]; %n=s^2+1
d=[1 2 5 0 0]; %d=s^2(s^2+2s+5)=s^4+2s^3+5s^2
disp(['Numerator = ' poly2str(n,'s')]);
disp(['Denominator = ' poly2str(d,'s')]);
[r,p,k]=residue(n,d)

Numerator = 5 s^2 + 8 s - 5
Denominator = s^4 + 2 s^3 + 5 s^2
r=
-1.0000 - 1.0000i
-1.0000 + 1.0000i
2.0000
-1.0000
p=
-1.0000 + 2.0000i
-1.0000 - 2.0000i
0
0
k=
[]
Note, first two roots are complex conjugate roots.
Get magnitude and phase from magnitude and phase of pfe Refer
to manual solution on web page listed above.
M=2*abs(r(1))
phi=angle(r(1))
M=
2.8284

%Magnitude of cosine
%Phase of cosine in radians

phi =
-2.3562
Get frequency and decay rate from location of pole
omega=abs(imag(p(1))) % omega has to be positive
alpha=-real(p(1))
omega =
2
alpha =
1

Plot the response


t=linspace(-1,4,1000);
f=(M*exp(-alpha*t).*cos(omega*t+phi) + r(3) + r(4)*t) .*
heaviside(t);
plot(t,f,'Linewidth',2);
xlabel('Time'); ylabel('f(t)'); grid;

Fourth Example - Order of numerator=order of denominator


To see this example worked out manually go to:
http://lpsa.swarthmore.edu/LaplaceXform/InvLaplace/InvLaplace
XformPFE.html#Order_of_numerator_polynomial_equals_order_o
f_denominator_
disp('Example 4: PFE: order of num=order of den');
Example 4: PFE: order of num=order of den
If the numerator and denominator have the same order, we get a
constant as part of the partial fraction expansion.

Define numerator and denominator polynomial.

n=[3 2 3];
%n=3s^2+2s + 3
d=[1 3 2];
%d=s^2+3s+2=(s+1)(s+2)
disp(['Numerator = ' poly2str(n,'s')]);
disp(['Denominator = ' poly2str(d,'s')]);
[r,p,k]=residue(n,d)
Numerator = 3 s^2 + 2 s + 3
Denominator = s^2 + 3 s + 2
r=
-11
4
p=
-2
-1
k=
3
Note this time that k is not empty, k=3.

Published with MATLAB 7.10

Integration
Definite and indefinite integrals, numeric approximation of
integrals, integration methods
MuPAD Functions
int

Definite and indefinite integrals

int::addpattern

Add patterns for integration

intlib::byparts

Integration by parts

intlib::changevar

Change of variable

intlib::intOverSet

Integration over a set

intlib::printWarnings Enable or disable warnings


numeric::gldata

Weights and abscissae of Gauss-Legendre


quadrature

numeric::gtdata

Weights and abscissae of GaussTschebyscheff quadrature

numeric::int

Numerical integration (the Float attribute of


Int )

numeric::ncdata

Weights and abscissae of Newton-Cotes


quadrature

numeric::quadrature Numerical integration ( Quadrature )

Examples and How To


Compute Indefinite Integrals

Compute Definite Integrals

Compute Multiple Integrals

Apply Standard Integration Methods Directly

Get Simpler Results

If an Integral Is Undefined

If MuPAD Cannot Compute an Integral

Concepts
Integration Utilities
Numeric Algorithms Library
Compute Indefinite Integrals
To integrate a mathematical expression f means to find an
expression F such that the first derivative of F is f. The expression
F is an antiderivative of f. Integration is a more complicated task
than differentiation. In contrast to differentiation, there is no
general algorithm for computing integrals of an arbitrary
expression. When you differentiate an expression, the result is
often represented in terms of the same or less complicated
functions. When you integrate an expression, the result often
involves much more complicated functions than those you use in
the original expression. For example, if the original expression
consists of elementary functions, you can get the result in terms of
elementary functions:

int(x + 1/(x^2), x)

The following integrand also consists of standard trigonometric


functions, but here the integrator cannot return the result in terms
of elementary functions. The antiderivative involves a special
function:
int(sin(x)/x, x)

When you compute an indefinite integral, MuPAD implicitly


assumes that the integration variable is real. The result of
integration is valid for all real numbers, but can be invalid for
complex numbers. You also can define properties of the integration
variables by using the assume function. The properties you specify
can interfere with the assumption that the integration variable is
real. If MuPAD cannot integrate an expression using your
assumption, the int function issues a warning. Use the
intlib::printWarnings function to switch the warnings on and off.
For example, switch on the warnings:
intlib::printWarnings(TRUE):

Suppose you want to integrate the following expression under the


assumption that the integration variable is positive. This
assumption does not conflict with the assumption that the variable
is real. The int command uses your assumption:
f := abs(x):
int(f, x) assuming x > 0

Integrate this expression under the assumption that x is an integer.


MuPAD cannot integrate the expression over a discrete subset of
the real numbers. The int command issues a warning, and then
integrates over the field of real numbers:
int(f, x) assuming x in Z_
Warning: Cannot integrate when 'x' has property 'Z_'. The
assumption that 'x' has the property 'R_' is used for integration.
[intlib::int]

For a discrete set of values of the integration variable, compute a


sum instead of computing an integral. See Summation for details.

Now integrate under the assumption that x is imaginary. The int


command cannot compute the integral of the expression over
imaginary numbers. It issues a warning and integrates the
expression over the domain of complex numbers:
assume(x, Type::Imaginary);
int(f, x)
Warning: Cannot integrate when 'x' has property '{x*I | x in R_}'.
The assumption that 'x' has the property 'C_' is used for integration.
[intlib::int]

For more information about the assumptions, see Properties and


Assumptions. Before you proceed with other computations, clear
the assumption on the variable x:
unassume(x):
Also, disable the warnings:
intlib::printWarnings(FALSE):

Compute Definite Integrals


For definite integration, the int command restricts the integration
variable x to the given range of integration.
int(sin(ln(x)), x = 0..5)

If the int command determines that an integral does not converge,


it returns the special value undefined:
int(exp(x*I), x = 1..infinity)

When the int command cannot compute an integral and also cannot
prove that the integral does not converge, it returns an unresolved
integral:
int(sin(cos(x)), x = 0..10)

For definite integrals, the int command restricts the integration to


the specified interval. If you use the assume function to set

properties on the integration variable, int temporarily overwrites


these properties and integrates over the specified interval. To
display warnings, set the value of intlib::printWarnings to TRUE:
intlib::printWarnings(TRUE):
assume(x > 0):
int(x, x = 1 .. 2);
int(x, x = -3 .. 1)
Warning: The assumption that 'x' has property '[1, 2]' instead of
given property '(0, infinity)' is used for integration. [int]

Warning: The assumption that 'x' has property '[-3, 1]' instead of
given property '(0, infinity)' is used for integration. [int]

After computing an integral, MuPAD restores the assumptions set


for integration variable. If you do not want the assumptions to
affect further computations, use the unassume function:
unassume(x)

MuPAD also makes implicit assumptions on the specified interval.


Suppose, you use the integration range as [a, b]. The system
assumes that both a and b represent real numbers, and that a < b
unless you clearly specify otherwise. If you set the value of
intlib::printWarnings to TRUE, MuPAD displays the warning
about using implicit assumptions:
int(heaviside(x - a), x = a..b)
Warning: Cannot decide if 'a <= b' is true, will temporarily assume
it is true. [int]

To avoid this implicit assumption, specify that a > b:


int(heaviside(x - a), x = a..b) assuming a > b

For further computations, disable the warnings:


intlib::printWarnings(FALSE):

Compute Multiple Integrals


To compute multiple integrals, use nested calls to int. For example,
compute the surface area and the volume of a sphere using
spherical coordinates.

Compute the expression for the surface area of a sphere. The


distance from the center of a sphere to the surface remains
constant, r = R. The angle changes its value from 0 to . The
angle changes its value from 0 to 2:
int(int(R^2*sin(phi), phi = 0..PI), chi = 0..2*PI)

Compute the expression for the volume of a sphere. The angles


accept the same values, but the distance from the center of any
point inside the sphere ranges from 0 to R. To find the volume,
compute the following triple integral:
Search MATLAB Documentation

Search R2012b D Search

R2012b
Phased Array System Toolbox
Waveforms, Transmitter, and Receiver
Waveforms

phased.MatchedFilter System object


Package: phased
Matched filter
Description
The MatchedFilter object implements matched filtering of an input
signal.
To compute the matched filtered signal:
1.

Define and set up your matched filter. See Construction.

2.

Call step to perform the matched filtering according to the


properties of phased.MatchedFilter. The behavior of step is
specific to each object in the toolbox.

Construction
H = phased.MatchedFilter creates a matched filter System object,
H. The object performs matched filtering on the input data.
H = phased.MatchedFilter(Name,Value) creates a matched filter
object, H, with each specified property Name set to the specified
Value. You can specify additional name-value pair arguments in
any order as (Name1,Value1,...,NameN,ValueN).
Properties
CoefficientsSource

Source of matched filter coefficients


Specify whether the matched filter
coefficients come from the Coefficients
property of this object or from an input
argument in step. Values of this property
are:
'Property' The Coefficients property
of this object specifies the
coefficients.
'Input

An input argument in each

port'

invocation of step specifies

the coefficients.
Default: 'Property'
Coefficients

Matched filter coefficients


Specify the matched filter coefficients as
a column vector. This property applies
when you set the CoefficientsSource
property to 'Property'. This property is
tunable.
Default: [1;1]

SpectrumWindow

Window for spectrum weighting


Specify the window used for spectrum
weighting using one of 'None',
'Hamming', 'Chebyshev', 'Hann', 'Kaiser',
'Taylor', or 'Custom'. Spectrum weighting
is often used with linear FM waveform to
reduce the sidelobes in the time domain.
The object computes the window length
internally, to match the FFT length.
Default: 'None'

CustomSpectrumWindowUser-defined window for spectrum


weighting
Specify the user-defined window for
spectrum weighting using a function
handle or a cell array. This property
applies when you set the
SpectrumWindow property to 'Custom'.
If CustomSpectrumWindow is a function
handle, the specified function takes the
window length as the input and generates
appropriate window coefficients.
If CustomSpectrumWindow is a cell
array, then the first cell must be a function
handle. The specified function takes the
window length as the first input argument,
with other additional input arguments if
necessary, and generates appropriate
window coefficients. The remaining
entries in the cell array are the additional
input arguments to the function, if any.
Default: @hamming

SpectrumRange

Spectrum window coverage region


Specify the spectrum region on which the
spectrum window is applied as a 1-by-2
vector in the form of
[StartFrequency EndFrequency] (in
hertz). This property applies when you set
the SpectrumWindow property to a value
other than 'None'.
Note that both StartFrequency and
EndFrequency are measured in baseband.
That is, they are within [-Fs/2 Fs/2],
where Fs is the sample rate that you
specify in the SampleRate property.
StartFrequency cannot be larger than
EndFrequency.
Default: [0 1e5]

SampleRate

Coefficient sample rate


Specify the matched filter coefficients
sample rate (in hertz) as a positive scalar.
This property applies when you set the
SpectrumWindow property to a value

other than 'None'.


Default: 1e6
SidelobeAttenuation

Window sidelobe attenuation level


Specify the sidelobe attenuation level (in
decibels) of a Chebyshev or Taylor
window as a positive scalar. This property
applies when you set the
SpectrumWindow property to
'Chebyshev' or 'Taylor'.
Default: 30

Beta

Kaiser window parameter


Specify the parameter that affects the
Kaiser window sidelobe attenuation as a
nonnegative scalar. Please refer to kaiser
for more details. This property applies
when you set the SpectrumWindow
property to 'Kaiser'.
Default: 0.5

Nbar

Number of nearly constant sidelobes in

Taylor window
Specify the number of nearly constant
level sidelobes adjacent to the mainlobe
in a Taylor window as a positive integer.
This property applies when you set the
SpectrumWindow property to 'Taylor'.
Default: 4
GainOutputPort

Output gain
To obtain the matched filter gain, set this
property to true and use the corresponding
output argument when invoking step. If
you do not want to obtain the matched
filter gain, set this property to false.
Default: false

Methods
clone

Create matched filter object with same property


values

getNumInputs

Number of expected inputs to step method

getNumOutputs Number of outputs from step method


isLocked

Locked status for input attributes and nontunable

properties
release

Allow property value and input characteristics


changes

step

Perform matched filtering

Examples
Construct a matched filter for a linear FM waveform.
hw = phased.LinearFMWaveform('PulseWidth',1e-4,'PRF',5e3);
x = step(hw);
hmf = phased.MatchedFilter(...
'Coefficients',getMatchedFilter(hw));
y = step(hmf,x);
subplot(211),plot(real(x));
xlabel('Samples'); ylabel('Amplitude');
title('Input Signal');
subplot(212),plot(real(y));
xlabel('Samples'); ylabel('Amplitude');
title('Matched Filter Output');

Apply the matched filter, using a Hamming window to do


spectrum weighting.
hw = phased.LinearFMWaveform('PulseWidth',1e-4,'PRF',5e3);
x = step(hw);
hmf = phased.MatchedFilter(...
'Coefficients',getMatchedFilter(hw),...

'SpectrumWindow','Hamming');
y = step(hmf,x);
subplot(211),plot(real(x));
xlabel('Samples'); ylabel('Amplitude');
title('Input Signal');
subplot(212),plot(real(y));
xlabel('Samples'); ylabel('Amplitude');
title('Matched Filter Output');

Apply the matched filter, using a custom Gaussian window for


spectrum weighting.
hw = phased.LinearFMWaveform('PulseWidth',1e-4,'PRF',5e3);
x = step(hw);
hmf = phased.MatchedFilter(...
'Coefficients',getMatchedFilter(hw),...
'SpectrumWindow','Custom',...
'CustomSpectrumWindow',{@gausswin,2.5});
y = step(hmf,x);
subplot(211),plot(real(x));
xlabel('Samples'); ylabel('Amplitude');
title('Input Signal');
subplot(212),plot(real(y));
xlabel('Samples'); ylabel('Amplitude');
title('Matched Filter Output');

Algorithms
The filtering operation uses the overlap-add method.
Spectrum weighting produces a transfer function

where w(F) is the window and H(F) is the original transfer


function.

For further details on matched filter theory, see [1]or [2].


References
[1] Richards, M. A. Fundamentals of Radar Signal Processing.
New York: McGraw-Hill, 2005.
[2] Skolnik, M. Introduction to Radar Systems, 3rd Ed. New York:
McGraw-Hill, 2001.
See Also
phased.CFARDetector | phased.StretchProcessor |
phased.TimeVaryingGain | pulsint | taylorwin

magphase(f, H)
Plot a transfer function's magnitude and phase
fourier1
Real Fourier series examples and creates movies
fourier2
Complex Fourier series examples with filtering
fourier3
Analyze speech spectra via spectrograms

siganalysis
Display signal waveform and calculate spectrogram
sampling
Explore time- and frequency-domain effects of sampling
adaptive
MMSE adaptive filter that preserves constants
digital
Various aspects of digital communication

Matched filter simulation


Compute Pr[e]
Error correcting codes
Capacity

function magphase(f,H)
% magphase(f,H) - plot the magnitude and phase of a transfer
function
% f - vector of frequencies
% H - complex transfer function
subplot(211)
loglog(f,abs(H));grid
ylabel('Log Magnitude');
title('Magnitude and Phase Plots');
subplot(212)
semilogx(f, angle(H)*180/pi); grid
ylabel('Angle (deg)'); xlabel('Frequency');
%
% Half-wave rectified sinusoid
%
t=[0:.001:2];
n = [0:50];
bn = zeros(1,length(n));
bn(2) = 1/2;

an = -(2/pi)*ones(1,length(n))./(n.*n-1); an(1) =
1/pi;an(2:2:length(n)) = 0;
hwrs = cumsum((bn'*ones(1,length(t)).*sin(2*pi*n'*t))...
+ (an'*ones(1,length(t)).*cos(2*pi*n'*t)));
Nterms = sum(an~=0);
M = moviein(Nterms,gcf);
for N = 1:2:length(n)
clf
subplot(211);
plot(t,hwrs(N,:));
axis([0 2 -.5 1.5]);
h = text(1.7,1.2,sprintf('N: %3d',N-1));
set(h,'fontsize',18);
h = xlabel('Time'); set(h,'fontsize',18);
h = ylabel('Amplitude'); set(h,'fontsize',18);
set(gca, 'fontsize',18);
subplot(212)
stem(n(1:N),an(1:N),'filled','r');
hold on
if N>1
stem(1,bn(2),'filled','b');
end
axis([min(n) max(n) -.5 .5]);
h = xlabel('Fourier Index'); set(h,'fontsize',18);
h = ylabel('Spectral amplitude'); set(h,'fontsize',18);
set(gca, 'fontsize',18);
grid
M(:,(N+1)/2) = getframe(gcf);
end
% Sine wave display
figure
plot(t,
(ones(length(t),1)*bn.*sin(2*pi*t'*n))+(ones(length(t),1)*an.*cos(
2*pi*t'*n)))
%

% Square Wave
%
figure('Units','normalized','Position',[.25,.25,.7,.7])
t=[0:.001:2];
n = [0:100];
an = zeros(size(n));
bn = ones(1,length(n))./n; bn(1) = 0; bn(3:2:length(n)) = 0;
sq = cumsum((4/pi)*(bn'*ones(1,length(t)).*sin(2*pi*n'*t)));
Nterms = sum(bn~=0);
M = moviein(Nterms, gcf);
for N = 2:2:length(n)
clf
subplot(211);
plot(t,sq(N,:));
axis([0 2 -1.5 1.5]);
h = text(1.7,1.2,sprintf('N: %3d',N-1));
set(h,'fontsize',18);
h = xlabel('Time'); set(h,'fontsize',18);
h = ylabel('Amplitude'); set(h,'fontsize',18);
set(gca, 'fontsize',18);
subplot(212)
stem(n(2:N),bn(2:N),'filled','r');
axis([min(n) max(n) 0 1]);
h = xlabel('Fourier Index'); set(h,'fontsize',18);
h = ylabel('Spectral amplitude'); set(h,'fontsize',18);
set(gca, 'fontsize',18);
grid
M(:,N/2) = getframe(gcf);
end
%
figure
plot(t,
(ones(length(t),1)*bn.*sin(2*pi*t'*n))+(ones(length(t),1)*an.*cos(
2*pi*t'*n)))
t=[0:.002:2];

N=200;
n = [0:N];
j = sqrt(-1);
%
% Square Wave
cn = 2*ones(1,length(n))./(j*pi*n);
cn(1:2:N+1) = 0; % Set even terms to zero
%
% Periodic pulses
%
delta = .1;
cn = exp(-j*pi*n*delta).*sin(pi*n*delta)./(pi*n);
cn(1) = delta;
%
% Half-wave rectified sinusoid
%
cn(1) = 1/pi;
cn(2) = -j*1/4;
cn(3:N+1) = -(1/pi)*ones(1,N-1)./([2:N].^2-1);
cn(4:2:N+1) = 0;
%
% Full-wave rectified sinusoid
%
cn(1) = 2/pi;
cn(2) = 0;
cn(3:N+1) = -(2/pi)*ones(1,N-1)./([2:N].^2-1);
cn(4:2:N+1) = 0;
%
% Form and plot Fourier series representations
%
x = cumsum([cn(1)*ones(1,length(t));zeros(N-1,length(t))]...
+(cn(2:N+1).'*ones(1,length(t)).*exp(j*2*pi*[1:N]'*t))... %
Positive integers
+(cn(2:N+1)'*ones(1,length(t)).*exp(-j*2*pi*[1:N]'*t))); %
Negative integers

figure(1);plot(t,x(N,:));set(gca,'fontsize',18);
% figure(1);plot(t,x);set(gca,'fontsize',18);
%
% Filter by modifying the Fourier series
%
f = n; % Assume period = 1;
%
% First order lowpasss filter
%
RC = 2;
H=ones(1,length(f))./(j*2*pi*f*RC+1);
figure(2)
subplot(211);
loglog(f,abs(H));set(gca,'fontsize',18);grid
subplot(212);
semilogx(f,angle(H)*180/pi);set(gca,'fontsize',18);grid
axis([0 N -90 0])
%
% First order highpass
%
RC = .05;
H=j*2*pi*f*RC./(j*2*pi*f*RC+1);
figure(2)
subplot(211);
loglog(f,abs(H));set(gca,'fontsize',18);grid
subplot(212);
semilogx(f,angle(H)*180/pi)grid
axis([0 N 0 90])
%
% Filter the signal x(t)
%
dn = cn.*H; % Multiply Fourier coefficients by transfer function
y = cumsum([dn(1)*ones(1,length(t));zeros(N-1,length(t))]...
+(dn(2:N+1).'*ones(1,length(t)).*exp(j*2*pi*[1:N]'*t))... %
Positive integers

+(dn(2:N+1)'*ones(1,length(t)).*exp(-j*2*pi*[1:N]'*t))); %
Negative integers
figure(3);
subplot(211);plot(t,x(N,:));set(gca,'fontsize',18);
subplot(212);plot(t,y(N,:));set(gca,'fontsize',18);a=axis;
a(3)=0;axis(a)
% figure(3);
% subplot(211);plot(t,x);subplot(212);plot(t,y);axis([0 2 -2 2])
% set(gca,'fontsize',18);
load speech
%
siganalysis(agb, Fs);
%
% Narrowband spectrogram
%
figure(1);
specgram(agb,512,Fs);
[Sn,Fn,Tn]=specgram(agb,512,Fs);
figure;scs_fric = gcf;
Tn(30)
semilogy(Fn,abs(Sn(:,30))); % Voiced fricative
figure;scs_vowel = gcf;
Tn(56)
semilogy(Fn,abs(Sn(:,56))); % Vowel
%
% Wideband spectrogram
%
specgram(agb,128,Fs);
[Sw,Fw,Tw]=specgram(agb,128,Fs);
figure(scs_fric);hold on
Tw(117)
semilogy(Fw,abs(Sw(:,117)),'r'); % Voiced fricative
figure(scs_vowel);hold on
Tw(220)
semilogy(Fw,abs(Sw(:,220)),'r'); % Vowel

function siganalysis(x, fs)


% signanalysis(x, fs)
% Plot the waveform of signal x and the spectrogram
% fs - sampling frequency
N = length(x);
T = N/fs; % duration in seconds
frame = fix(.05*fs); % 50 ms frame
for m=1:fix(N/frame)
rms(m) = sqrt(sum(x(1+(m-1)*frame:m*frame).^2)/frame);
end
theta_rms = .0;
offset = frame*(min(find(rms>theta_rms)))+1;
xend = min(frame*(max(find(rms>theta_rms)))+5*frame,N);
%
M = 5; % Number of waveform plots/figure
Tframe = .2; % duration of each plot in seconds
L = ceil((xend-offset)/(M*Tframe*fs)); % number of figures
for l=1:L
figure(l+1); clf
for m=1:M
i1=offset+fix(((l-1)*M*Tframe+(m-1)*Tframe)*fs);
i2 = i1 + fix(Tframe*fs);
if i2 > xend
m=m-1;
drawnow
break
end
subplot(M,1,m);
time = ([i1:i2]-offset)/fs;
plot(time, x(i1:i2));
axis([time(1) time(1)+Tframe -1 1]);
end
if m > 0
subplot(M,1,1); title(sprintf('Waveform Plot %d',l));

Amplitude');
else
end

subplot(M,1,fix((m+1)/2)); ylabel('Signal
subplot(M,1,m); xlabel('Time (seconds)');
drawnow
clf

end
%
figure(1)
specgram(x(offset:xend),256,fs);
title('Spectrogram')

% Example of sampling
fs = 1000; % Sampling Rate
f = 60; % Frequency of sinusoid
T = 1; % length of time axis
N = 2^ceil(log2(fs*T)); % Transform length
%
t = [0:1/fs:T];
sinewave=sin(2*pi*f*t);
sq = infclip(sinewave);
%
clf;
signal = sq;
spectrum = fft(signal, N);
subplot(211)
plot(t,signal);
hold on
plot(t,signal,'or');
current_axis = axis;
current_axis(2) = .1;
current_axis(3:4) = 1.5*current_axis(3:4);

axis(current_axis);
subplot(212)
f_axis = [0:1/N:.5]*fs;
plot(f_axis, abs(spectrum(1:N/2+1)));
%
% Amplitude quantization
%
f = 64;
sinewave=sin(2*pi*f*t);
b=4;
levels=2^b;
q_sine = fix(levels/2*sinewave);
clf;
signal = sq;
spectrum = fft(q_sine, N);
subplot(211)
plot(t,q_sine);
hold on
plot(t,q_sine,'or');
current_axis = axis;
current_axis(2) = .1;
current_axis(3:4) = 1.5*current_axis(3:4);
axis(current_axis);
subplot(212)
f_axis = [0:1/N:.5]*fs;
semilogy(f_axis, abs(spectrum(1:N/2+1)));
grid
Fs = 5000; % Sampling frequency
t= [0:1/Fs:1];
p = 40; % Linear predictive order
An = 0.0; % Noise amplitude
%
% Least-squares FIR filter that preserves constants
f1 = 60; f2 = 180;

x=1.5 + sin(2*pi*f1*t) + sin(2*pi*f2*t) + An*randn(size(t));


corr = xcorr(x,x,p,'biased');
R = toeplitz(corr(p+1:2*p+1));
b = R\ones(p+1,1);
b = b/sum(b);
boxcar = ones(1,p+1)/(p+1);
y = filter(b,1,x);
yave = filter(boxcar,1,x);
L = 200;
subplot(211);
plot(t(1:L),x(1:L),t(1:L),yave(1:L),'g',t(1:L),y(1:L),'r');
subplot(212);
N = 256;
f = [0:N/2]*Fs/N;
H = fft(b, N);
Hboxcar = fft(boxcar, N);
semilogy(f,abs(H(1:N/2+1)),'r',f,abs(Hboxcar(1:N/2+1)),'g');
grid
ax = axis;
line([f1 f1],[ax(3) ax(4)]);line([f2 f2],[ax(3) ax(4)]);

% Various routines that simulate or compute aspects of digital


communication systems
%
% Simulate matched filter receiver
figure(1);
N = 100;
noise_amp = 3;
signal_set = 'bpsk'; % either 'bpsk', 'ask', or 'fsk'

bits = ['1', '0', '1', '0', '0', '1'];


%
if strcmp(signal_set, 'bpsk')
signal1 = ones(1,N);
signal0 = -signal1;
elseif strcmp(signal_set,'fsk')
signal1 = sqrt(2)*sin(2*pi*2*[0:N-1]/N);
signal0 = sqrt(2)*sin(2*pi*3*[0:N-1]/N);
elseif strcmp(signal_set, 'ask');
signal1 = ones(1,N);
signal0 = zeros(1,N);
else
perror(sprintf('Unknown signal set %s\n',signal_set));
end
color0='r';color1='b';
x = []; xcolor = [];
for n=1:length(bits)
x=[x eval(strcat('signal',bits(n)))];
xcolor = [xcolor eval(strcat('color',bits(n)))];
end
% Send signal through white noise channel
r = x + noise_amp*randn(1,length(x));
% Run matched filters
y1=filter(signal1(N:-1:1),1,r);
y0=filter(signal0(N:-1:1),1,r);
% Graphics
subplot(211)
t=[0:length(r)-1];
plot(t,r);hold on
a = axis;
xp=x*(0.75*max(abs([a(3) a(4)])/max(x)));
for n=1:length(bits)
plot(t((n-1)*N+1:n*N),xp((n-1)*N+1:n*N),[xcolor(n) '--']);
h = text((n-1)*N+N/2,max(xp),bits(n));
set(h,'fontsize',16);set(h,'color',xcolor(n));

end
for n=N*[1:length(bits)],h=line([n n],a(3:4));set(h,'linestyle','-');end
h=title('Received signal');set(h,'fontsize',18);
hold off
subplot(212)
plot(t,y0,color0,t,y1,color1)
a = axis;
for n=1:length(bits)
if y1(n*N)>= y0(n*N)
h = text(n*N-10,.75*a(4),'1');
set(h,'fontsize',16);set(h,'color',color1);
if bits(n) == '0'
set(h,'fontweight','bold');
end
else
h = text(n*N-10,.75*a(4),'0');
set(h,'fontsize',16);set(h,'color',color0);
if bits(n) == '1'
set(h,'fontweight','bold');
end
end
end
for n=N*[1:length(bits)],h=line([n n],a(3:4));set(h,'linestyle','-');end
h=title('Matched Filter Output');set(h,'fontsize',18);
%
% Compute Pr[e] curves
%
figure(2)
snrdb = [-10:.5:12];
snr = 10.^(snrdb/10);
p_bpsk = Q(sqrt(2*snr));
p_fsk = Q(sqrt(snr));

h=semilogy(snrdb,p_bpsk,snrdb,p_fsk,'r--');grid;axis([-10 12 10^(8) 1])


set(gca,'fontsize',18);
h=xlabel('Signal-to-Noise Ratio (dB)');set(h,'fontsize',18);
h=ylabel('Bit Error Probability');set(h,'fontsize',18);
legend('BPSK','FSK');
%
% Error Correction (Repetition Code)
%
figure(3)
snrdb = [-10:.5:12];
snr = 10.^(snrdb/10);
p_bpsk = Q(sqrt(2*snr));
pb_bpsk = p_bpsk;
pb_rep = 1-(1-p_bpsk).^3-3*p_bpsk.*(1-p_bpsk).^2;
p_31 = Q(sqrt(2*snr/3)); % Same transmission transmission time
pb_31 = p_31;
semilogy(snrdb,pb_bpsk,'b-',snrdb,pb_31,'r--',snrdb,pb_rep,'k-.');
grid;axis([-10 12 10^(-15) 1])
set(gca,'fontsize',18);
h=xlabel('Signal-to-Noise Ratio (dB)');set(h,'fontsize',18);
h=ylabel('Block Error Probability');set(h,'fontsize',18);
legend('No ECC','Same time/data bit','Length 3 Repetition Code')
title('Repetition Code (3,1)')
%
% Hamming Code Performance Curves
%
figure(4)
snrdb = [-10:.5:12];
snr = 10.^(snrdb/10);
p_bpsk = Q(sqrt(2*snr));
p_31 = Q(sqrt(2*1/3*snr));
p_74 = Q(sqrt(2*4/7*snr));
p_1511 = Q(sqrt(2*11/15*snr));
p_3126 = Q(sqrt(2*26/31*snr));

pb_uc1 = p_bpsk;
pb_uc4 = 1-(1-p_bpsk).^4;
pb_uc11 = 1-(1-p_bpsk).^11;
pb_uc26 = 1-(1-p_bpsk).^26;
pb_hamming31 = 1-(1-p_31).^3-3*p_31.*(1-p_31).^2;
pb_hamming74 = 1-(1-p_74).^7-7*p_74.*(1-p_74).^6;
pb_hamming1511 = 1-(1-p_1511).^15-15*p_1511.*(1p_1511).^10;
pb_hamming3126 = 1-(1-p_3126).^31-31*p_3126.*(1p_3126).^30;
clf
subplot(2,2,1);
semilogy(snrdb,pb_uc1,'k-',snrdb,pb_hamming31,'k-.');
grid;axis([-10 12 10^(-10) 1]);
h=ylabel('Block Error Probability'); set(h,'fontsize',18);
h = title('(3,1) Hamming Code'); set(h,'fontsize',18);
set(gca,'fontsize',18);
subplot(2,2,2);
semilogy(snrdb,pb_uc4,'b-',snrdb,pb_hamming74,'b-.');
grid;axis([-10 12 10^(-10) 1]);
h = title('(7,4) Hamming Code'); set(h,'fontsize',18);
set(gca,'fontsize',18);
subplot(2,2,3);
semilogy(snrdb,pb_uc11,'r-',snrdb,pb_hamming1511,'r-.');
grid;axis([-10 12 10^(-10) 1]);
h=ylabel('Block Error Probability'); set(h,'fontsize',18);
h=xlabel('Signal-to-Noise Ratio (dB)'); set(h,'fontsize',18);
h = title('(15,11) Hamming Code'); set(h,'fontsize',18);
set(gca,'fontsize',18);
subplot(2,2,4);
semilogy(snrdb,pb_uc26,'g-',snrdb,pb_hamming3126,'g-.');

grid;axis([-10 12 10^(-10) 1]);


h=xlabel('Signal-to-Noise Ratio (dB)');% set(h,'fontsize',18);
h = title('(31,26) Hamming Code'); set(h,'fontsize',18);
set(gca,'fontsize',18);
legend('Uncoded','Hamming Code',3);
%
% Capacity Calculations
%
figure(5)
p=[0:.01:.5];
C=1+p.*log2(p)+(1-p).*log2(1-p);
C(1) = 1;
subplot(211)
plot(p,C)
set(gca,'fontsize',18);grid
h = xlabel('Error Probability');set(h,'fontsize',18);
h = ylabel('Capacity (bits)');set(h,'fontsize',18);
subplot(212)
C=1+p_bpsk.*log2(p_bpsk)+(1-p_bpsk).*log2(1-p_bpsk);
plot(snrdb,C);
set(gca,'fontsize',18);grid;legend('Capacity using BPSK')
h = xlabel('Signal-to-Noise Ratio (dB)');set(h,'fontsize',18);
h = ylabel('Capacity (bits)');set(h,'fontsize',18);

Chegg Home
search
Search for

Homework Help
eTextbooks
Sign In
Help

home / homework help / questions and answers / engineering / electrical


engineering / write a matlab program to...

Matlab code for a pulse compression filter, two point targets.


Anonymous answer rating percentage100%Answers Rated %
Write a matlab program to compute and plot the output of a pulse
compression filter for two point targets. Do this for two cases when
the points are resolvable and when they are not resolvable. Use
typical radar parameters.
Electrical Engineering
Answers (1)

Rating:3 Stars
Anonymous - 26 minutes later
In Radars, range resolution and long range of operation are
the two important aspects. Long range operation means the
maximum distance over which radar can detect the targets.
The radar transmit modulated pulses to take the advantages
of better processing gain and resolution of these waveforms
are compared to continuous wave pulse. Radar Echo of these
modulated signals are received, it has to be processed in filter
matched to the modulating waveform to get the best SNR
gain at the output.
The matched filtering operation is done by Pulse
compression filter. The matched filter is filter which gives
best SNR (2E/N) by matching the transfer function of the
filter with the time delayed version of the signal which is
applied at the input of the filter. Designing of matched filter

involves various DSP algorithms Such as Overlap add/save,


FFT Correlation which employ FFT and IFFT.
the matlab codei already had in stock for my project with
sligh modifications is given,
tic;
clc;
clf;
BW=5*10^6;%bandwidth
T=51.2*10^-6;%pulse width
fc=0;
n=fix(2*BW*T+1);% sampling points
sampling_interval = T / n;
freqlimit = 0.5/ sampling_interval;
alpha=BW/(T);%chirp rate
disp(alpha);
t=linspace(-T/2,T/2,n);%time interval
ichannel1=cos(2*pi*((fc)*t+alpha*t.^2));%real part
%imaginary part
qchannel2=sin(2*pi*((fc)*t+alpha*t.^2));
LFMD=(ichannel1+(1i.*qchannel2));%complex part of base
band signal
LFMD(2:1:10)=0;
LFMD(504:1:511)=0;
disp(LFMD);
% freqmin=fc+BW/2;%minimum frequency at t= -T/2;
% freqmax=fc-BW/2;%maximum frequnecy at t= T/2;
freq = linspace(-freqlimit/2,freqlimit/2,n);
FLFMD=fftshift(fft(LFMD));%frequency domain of lfm
[lfm,frei,flfm]=lffm1(BW,n,T);
figure(1)
subplot(2,1,1)
plot(freq,abs((FLFMD)),frei,abs(flfm));

grid;
xlabel('frequency');
ylabel('amplitude')
title('baseband and input signals of pulse compression filter');
%plot(t,((LFMD)),'k')
% plot(t,(lfm),'k');
rep=fliplr(LFMD);
N=4097;%intilization of buffer value
ovr=1638;%overlap value
%for 10% overlap calling function
if ovr<=N*0.1
[YN11,t1]=ovsav1(LFMD,lfm,N,ovr);
subplot(2,1,2)
plot(t1,(YN11),'k');
grid;
%for 20% overlap calling function
elseif ovr<=N*0.2
[YN11,t1]=ovsav2(LFMD,lfm,N,ovr);
subplot(2,1,2)
plot(t1,(YN11),'k');
grid;
%for 25%overlap calling function
elseif ovr<=N*0.25
[YN11,t1]=ovsav3(LFMD,lfm,N,ovr);
subplot(2,1,2)
plot(t1,(YN11),'k');
grid;
%for 30%overlap calling function
elseif ovr<=N*0.3
[YN11,t1]=ovsav4(LFMD,lfm,N,ovr);
subplot(2,1,2)
plot(t1,(YN11),'k');
grid;
%for 40%overlap calling function
elseif ovr<=N*0.4

[YN11,t1,n1]=ovsav5(LFMD,lfm,N,ovr,n);
subplot(2,1,2)
plot(t1,(YN11));
xlabel('time domain')
ylabel('amplitude')
title('output of the pulse compression filter using overlap save
method')
grid;
else
break;
end
toc;
You must sign in to answ er que

Sign In

Open Advanced Editor

Answer
Ask a new question
More than 200 experts are waiting to help you now...
ABOUT CHEGG

Media Center
Chegg For Good
Privacy Policy
Your CA Privacy Rights
Terms of Use
General Policies
Intellectual Property Rights

RESOURCES

Site Map

Mobile
Publishers
Brand Partners
Join Our Affiliate Program
Flashcards App
Campus Crew

HELPFUL LINKS

Return Your Books


eTextbooks
Used Textbooks
Cheap Textbooks
College Textbooks
Sell Textbooks
Homework Help
Chegg Coupon
Scholarships
Solutions Manual

COMPANY

Management
Blog
Jobs
Customer Service
Give Us Feedback

Chegg Plants Trees

2003-2012 Chegg Inc. All rights reserved.


Over 5 million trees planted

Chapter 13 is a walk-through tutorial of a number of


basic wavelet algorithms. In the book the tutorial is
printed as ready-to-type Matlab code. To ease the
typing all six tutorials are given here in ASCII
format. You will also need the toolbox UviWave.
Note that the Matlab code below is in m-files, which
suggests that they are Matlab functions ready to run.
They are Matlab functions, and they can be
executed from the Matlab prompt. However, they
are meant to be typed in line by line, so youll get
the most of the tutorial by executing the functions
one line at a time, for instance by copy and paste the
code onto the Matlab prompt. The left most column
has links to ASCII format code shown directly in the

browser. You can also copy and paste this code


directly to the Matlab prompt.
In Copy & Paste
ready format

With line
numbers

Without line
numbers

1. Multiresolution
analysis I

Tutor-1num.m

Tutor-1.m

2. Multiresolution
analysis II

Tutor-2num.m

Tutor-2.m

3. Frequency
Properties I

Tutor-3num.m

Tutor-3.m

4. Frequency
Properties II

Tutor-4num.m

Tutor-4.m

5. Wavelet Packets
Used for Denoising

Tutor-5num.m

Tutor-5.m

6. Best Basis
Algorithm

Tutor-6num.m

Tutor-6.m

All files zipped.

Tutornum.zip

Tutor.zip

All tutorials in one


file.

Tutor-1-6num.m

Tutor-1-6.m

To save the files to your own disk, right click and


choose Save target as ... or Save Link as ....
Alternatively, you can hold down Shift while left
clicking the file names.

Ripples in Mathematics - The Discrete Wavelet


Transform. Springer Verlag Berlin Heidelberg 2001
Web master: Anders la Cour-Harbo, Aalborg
University, Denmark.
MATLAB is a registred trademark of The
MathWorks, Inc.

S =
sin([1:500]*2*pi/32);
1.2 > plot(S(1:32))
1.3 > plot(S)
1.4 > [h,g,rh,rg] =
daub(8);
1.5 > help multires
1.6 > y =
multires(S,h,rh,g,rg,4
);
1.7 > size(y)
1.8 > help split
1.9 > split(y)
See figure 13.1

1.10 > S =
sin([1:500]*2*pi/5);
1.11 > y =
multires(S,h,rh,g,rg,4
);
1.12 > figure
1.13 > split(y)
%
See figure 13.1
[1. Multiresolution Analysis I]
[2. Multiresolution Analysis II]
[3. Frequency Properties I]
[4. Frequency Properties II]
[5. Wavelet Packets Used for
Denoising]

[6. Best Basis Algorithm]

close all
2.2 > S = sin([1:512]/512*2*pi*5);
2.3 > S(200) = 2;
2.4 > S(400) = 2;
2.5 > plot(S)
% See figure 13.2
2.6 > y = multires(S,h,rh,g,rg,4);
2.7 > split(y)
% See figure 13.2
2.8 > figure
2.9 > plot(sum(y,1)-S)
2.10 > plot(y(1,:)+y(2,:)+y(3,:) +y(4,:)+y(5,:)-S)
2.11 > figure
2.12 > plot(y(1,:)+y(2,:)+y(3,:)+y(4,:))
2.13 > hold on
2.14 > plot(y(5,:))
2.15 > yt = wt(S,h,g,4);
2.16 > figure
2.17 > isplit(yt,4,'','r.')
2.18 > yt(33:64) = zeros(1,32);
2.19 > yr = iwt(yt,rh,rg,4);
2.20
2.21
2.22
2.23
2.24

>
>
>
>
>

figure
subplot(211)
plot(S,'b')
hold on
plot(yr,'r')

2.25 > subplot(212)


2.26 > plot(S-yr)

3.1 > close all


3.2 > S = sin([1:2000].^2/1300);
3.3 > specgram(S)
3.4
3.5
3.6
3.7

>
>
>
>

% See figure 13.3

[h,g,rh,rg]=daub(16);
y = multires(S,h,rh,g,rg,4);
figure
split(y)
% See figure 13.3

4.1 >
[h,g,rh,rg]=wspline(3,15);
4.2 > h
4.3 > g
4.4 > s1 =
[sin([1:1000]/1000*2*pi*20)
zeros(1,1000)];
4.5 > s2 = [zeros(1,1000)
sin([1:1000]/1000*2*pi*90)]
;
4.6 > s3 = [zeros(1,1200)

sin([1:400]/400*2*pi*2)
zeros(1,400)];
4.7 > s4 = [zeros(1,250)
sin([1:250]/250*2*pi*125+pi
/2) zeros(1,250) ...
sin([1:500]/500*2*pi*250+pi
/2) zeros(1,750)];
4.8 >
4.9 >
4.10 >
4.11 >
4.12 >
4.13 >
4.14 >
4.15 >
figure

subplot(511)
plot(s1)
subplot(512)
plot(s2)
subplot(513)
plot(s3)
subplot(514)
plot(s4)
% See
13.4

4.16 > S = s1+s2+s3+s4;


4.17 > s5 =
randn(1,2000)/8;
4.18 > subplot(515)
4.19 > plot(s5)
% See
figure 13.4
4.20
4.21
4.22
4.23
4.24

>
>
>
>
>

figure
subplot(211)
plot(S)
subplot(212)
plot(S+s5)

4.25 > ym1 =


multires(S,h,rh,g,rg,5);
4.26 > figure
4.27 > split(ym1)
4.28 > for n=1:6
% See
figure 13.5
subplot(6,1,n)
set(gca, 'YLim',
[-2 2])
end
4.29 > for n=1:6,

subplot(6,1,n), set(gca,
'YLim', [-2 2]), end
4.30
4.31
4.32
256)
4.33

> figure
> subplot(211)
> specgram(S, 2048, 1,
> caxis([-50 10])

4.34 > subplot(212)


4.35 > specgram(S, 2048, 1,
32)
4.36 > caxis([-50 10])
4.37 > ym2 =
multires(S+s5,h,rh,g,rg,5);
4.38 > figure
4.39 > split(ym2)
4.40 > for n=1:6
% See
figure 13.5
subplot(6,1,n)
set(gca, 'YLim',
[-2 2])
end

5.1 > S = sin([1:4096].^2/5200);


5.2 > specgram(S,1024,8192,256,192)
5.3 > colorbar
5.4 > caxis([-35 35])
5.5 > colorbar
5.6 > sound(S,8192)
5.7
5.8
5.9
5.10
5.11
5.12
5.13
5.14

>
>
>
>
>
>
>
>

noise = randn(1,4096)/10;
figure
specgram(S+noise,1024,8192,256,192)
caxis([-35 35])
figure
specgram(noise,1024,8192,256,192)
caxis([-35 35])
sound(S+noise,8192)

5.15 > [h,g,rh,rg]=wspline(3,9);


5.16 > [h,g,rh,rg]=symlets(30);
5.17 > y = wpk(S,h,g,0);
5.18 > figure
5.19 > for n=1:5
% See figure 13.6
subplot(5,1,n)
plot(y(:,n))
set(gca, 'XLim', [0 4096], 'XTick', [0:1024:4096])
end
5.20 > yn = wpk(S+noise,h,g,0);
5.21 > figure
5.22 > for n=1:5
subplot(5,1,n)
plot(yn(:,n))
set(gca, 'XLim', [0 4096], 'XTick', [0:1024:4096])
end
5.23
5.24
5.25
5.26

>
>
>
>

figure
plot(y(:,7))
hold on
plot(yn(:,7),'r')

5.27 > zoom


5.28 > figure; plot(sort(abs(yn(:,7))))
5.29 > yc = yn(:,7) .* (abs(yn(:,7)) > 1);
5.30 > yr = iwpk(yc,rh,rg,0,6*ones(1,64));
5.31
5.32
5.33
5.34

>
>
>
>

figure
specgram(yr,1024,8192,256,192) % See figure 13.6
caxis([-35 35])
sound(yr, 8192)

5.35
5.36
5.37
5.38

>
>
>
>

figure
specgram((S+noise)-yr',1024,8192,256,192)
caxis([-35 35])
sound(yr'-(S+noise), 8192)

5.39 > figure


5.40 > specgram(yr'-S,1024,8192,256,192)

5.41 > caxis([-35 35])


5.42 > sound(yr'-S), 8192)
5.43 > close all
5.44 > while 1
Bound = input('Bound (return to quit): ');
if isempty(Bound) break; end
yc = yn(:,7) .* (abs(yn(:,7)) > Bound);
yr = iwpk(yc,rh,rg,0,6*ones(1,64));
figure(1)
clf
specgram(yr,1024,8192,256,192)
caxis([-35 35])
sound(yr,8192)
end
S = sin([1:32].^2/30);
6.2 > S = S / norm(S);
6.3 > plot(S)
6.4 > [h,g,rh,rg] = daub(6);
6.5 > [basis,v,total] =
pruneadd(S,h,g,'shanent');
6.6 > basis
6.7 > plot(v)

6.8 > total


6.9 > shanent(v)
6.10 > y = wpk(S,h,g,0);
6.11 > size(y)
6.12 > CostValue = [ ];
6.13 > for j=0:5
for k=0:2^j-1
Element = y(1+k*2^(5-j):(k+1)*2^(5j),j+1);
CostValue = [CostValue
shanent(Element)];
end
end
6.14 > Old_CostValue = CostValue
6.15 > CostValue(1)-total
6.16 > b = [zeros(1,31) ones(1,32)];
6.17 > Index = 31;
6.18 > for j = 4:-1:0
for k = 0:2^j-1
tmp =
CostValue(2*Index)+CostValue(2*Index+1);
if CostValue(Index) < tmp
b(Index) = 1;
else
CostValue(Index) = tmp;
end
Index = Index - 1;
end
end
6.19 > Old_CostValue - CostValue
6.20 > CostValue(1)-total
6.21 > for j=1:31
b(2*j) = b(2*j) + 2*b(j);
b(2*j+1) = b(2*j+1) + 2*b(j);
end
6.22 > b = (b == 1);

6.23 > S2 = iwpk(v,rh,rg,0,basis);


6.24 > plot(S2-S)
6.25 > tree(basis)
6.26 > figure
6.27 > tfplot(basis)
6.28 > figure
6.29 > plot(sort(abs(v)))
6.30 > hold on
6.31 > plot(sort(abs(S)),'r')
6.32 > S = sin([1:512].^2/512);
6.33 > noise = randn(1,512)/2;
6.34 > [B,A] = butter(2,[0.2 0.6]);
6.35 > S2 = S + filter(B,A,noise);
6.36 > [h,g,rh,rg] = daub(10);
6.37 > y = wpk(S2,h,g,0);
6.38 > [basis,v]=pruneadd(S2,h,g,'shanent');
6.39 > tree(basis)
6.40
6.41
6.42
6.43

>
>
>
>

plot(sort(abs(S2)),'b')
hold on
plot(sort(abs(y(:,2:end))),'k')
plot(sort(abs(v)),'r')

Multivariate Wavelet Denoising


The purpose of this example is to show the features of multivariate
denoising provided in Wavelet Toolbox.
Multivariate wavelet denoising problems deal with models of the
form

where the observation X is p-dimensional, F is the deterministic


signal to be recovered, and e is a spatially-correlated noise signal.
This example uses a number of noise signals and performs the
following steps to denoise the deterministic signal.
Loading a Multivariate Signal
To load the multivariate signal, type the following code at the
MATLAB prompt:
load ex4mwden
whos
Name
Size
covar
4x4
x
1024x4
x_orig
1024x4

Bytes Class

Attributes

128 double
32768 double
32768 double

Usually, only the matrix of data x is available. Here, we also have


the true noise covariance matrix covar and the original signals
x_orig. These signals are noisy versions of simple combinations of
the two original signals. The first signal is "Blocks" which is
irregular, and the second one is "HeavySine" which is regular,
except around time 750. The other two signals are the sum and the

difference of the two original signals, respectively. Multivariate


Gaussian white noise exhibiting strong spatial correlation is added
to the resulting four signals, which produces the observed data
stored in x.
Displaying the Original and Observed Signals
To display the original and observed signals, type:
kp = 0;
for i = 1:4
subplot(4,2,kp+1), plot(x_orig(:,i)); axis tight;
title(['Original signal ',num2str(i)])
subplot(4,2,kp+2), plot(x(:,i)); axis tight;
title(['Observed signal ',num2str(i)])
kp = kp + 2;
end

The true noise covariance matrix is given by:


covar
covar =
1.0000
0.8000
0.6000
0.7000

0.8000
1.0000
0.5000
0.6000

0.6000
0.5000
1.0000
0.7000

0.7000
0.6000
0.7000
1.0000

Removing Noise by Simple Multivariate Thresholding


The denoising strategy combines univariate wavelet denoising in
the basis, where the estimated noise covariance matrix is diagonal
with noncentered Principal Component Analysis (PCA) on
approximations in the wavelet domain or with final PCA.
First, perform univariate denoising by typing the following lines to
set the denoising parameters:
level = 5;
wname = 'sym4';
tptr = 'sqtwolog';
sorh = 's';
Then, set the PCA parameters by retaining all the principal
components:
npc_app = 4;
npc_fin = 4;
Finally, perform multivariate denoising by typing:
x_den = wmulden(x, level, wname, npc_app, npc_fin, tptr, sorh);
Displaying the Original and Denoised Signals

To display the original and denoised signals type the following:


clf
kp = 0;
for i = 1:4
subplot(4,3,kp+1), plot(x_orig(:,i)); axis tight;
title(['Original signal ',num2str(i)])
subplot(4,3,kp+2), plot(x(:,i)); axis tight;
title(['Observed signal ',num2str(i)])
subplot(4,3,kp+3), plot(x_den(:,i)); axis tight;
title(['Denoised signal ',num2str(i)])
kp = kp + 3;
end

Improving the First Result by Retaining Fewer Principal


Components

We can see that, overall, the results are satisfactory. Focusing on


the two first signals, note that they are correctly recovered, but we
can improve the result by taking advantage of the relationships
between the signals, leading to an additional denoising effect.
To automatically select the numbers of retained principal
components using Kaiser's rule, which retains components
associated with eigenvalues exceeding the mean of all eigenvalues,
type:
npc_app = 'kais';
npc_fin = 'kais';
Perform multivariate denoising again by typing:
[x_den, npc, nestco] = wmulden(x, level, wname, npc_app, ...
npc_fin, tptr, sorh);
Displaying the Number of Retained Principal Components
The second output argument npc is the number of retained
principal components for PCA for approximations and for final
PCA.
npc
npc =
2

As expected, because the signals are combinations of two original


signals, Kaiser's rule automatically detects that only two principal
components are of interest.
Displaying the Estimated Noise Covariance Matrix

The third output argument nestco contains the estimated noise


covariance matrix:
nestco
nestco =
1.0784
0.8333
0.6878
0.8141

0.8333
1.0025
0.5275
0.6814

0.6878
0.5275
1.0501
0.7734

0.8141
0.6814
0.7734
1.0967

As it can be seen by comparing it with the true matrix covar given


previously, the estimation is satisfactory.
Displaying the Original and Final Denoised Signals
To display the original and final denoised signals type:
kp = 0;
for i = 1:4
subplot(4,3,kp+1), plot(x_orig(:,i)); axis tight;
title(['Original signal ',num2str(i)])
subplot(4,3,kp+2), plot(x(:,i)); axis tight;
title(['Observed signal ',num2str(i)])
subplot(4,3,kp+3), plot(x_den(:,i)); axis tight;
title(['Denoised signal ',num2str(i)])
kp = kp + 3;
end

These results are better than those previously obtained. The first
signal, which is irregular, is still correctly recovered, while the
second signal, which is more regular, is better denoised after this
second stage of PCA.
Learning More About Multivariate Denoising
You can find more information about multivariate denoising,
including some theory, simulations, and real examples, in the
following reference:
M. Aminghafari, N. Cheze and J-M. Poggi (2006), "Multivariate
denoising using wavelets and principal component analysis,"
Computational Statistics & Data Analysis, 50, pp. 2381-2398.
Was this topic helpful?
Try MATLAB, Simulink, and Other Products

Get trial now

Join the conversation

Preventing Piracy
Privacy Policy
Trademarks
Patents
Site Help

1994-2012 The MathWorks, Inc.


Search R2012

Wavelet Toolbox

Wavelet Toolbox Examples

Multisignal 1-D Wavelet Analysis


A 1-D multisignal is a set of 1-D signals of same length stored as a
matrix organized rowwise (or columnwise).
The purpose of this example is to show how to analyze, denoise or
compress a multisignal, and then to cluster different
representations or simplified versions of the signals composing the
multisignal.
In this example, the signals are first analyzed and different
representations or simplified versions are produced:

Reconstructed approximations at given levels,

Denoised versions,

Compressed versions.

Denoising and compressing are two of the main applications of


wavelets, often used as a preprocessing step before clustering.
The last step of this example performs several clustering strategies
and compare them. It allows to summarize a large set of signals
using sparse wavelet representations.
Load and Plot a Multisignal
To illustrate these capabilities, let us consider a real-life
multisignal representing 35 days of an electrical load consumption,
centered and standardized.
load elec35_nor;
% Load normalized original data.
X = signals;
[nbSIG,nbVAL] = size(X);
plot(X','r')
axis tight
title('Original Data: 35 days of electrical consumption')
xlabel('Minutes from 1 to 1440')

We can see that the signals are locally irregular and noisy but
nevertheless three different general shapes can be distinguished.
Surface Representation of Data
In order to highlight the periodicity of the multisignal, let us now
examine the data using a 3-D representation.
surf(X);
shading interp
axis tight
title('Original Data: 35 days of electrical consumption')
xlabel('Minutes from 1 to 1440','Rotation',4)
ylabel('Days from 1 to 35','Rotation',-60)
set(gca,'View',[-13.5 48]);

The five weeks represented can now be seen more clearly.


Multisignal Row Decomposition
Perform a wavelet decomposition at level 7 using the ' sym4 '
wavelet.
dirDec = 'r';
% Direction of decomposition
level = 7;
% Level of decomposition
wname = 'sym4';
% Near symmetric wavelet
decROW = mdwtdec(dirDec,X,level,wname);
The generated decomposition structure is as follows:
decROW
decROW =
dirDec: 'r'

level: 7
wname: 'sym4'
dwtFilters: [1x1 struct]
dwtEXTM: 'sym'
dwtShift: 0
dataSize: [35 1440]
ca: [35x18 double]
cd: {1x7 cell}
Signals and Approximations at Level 7
Let us reconstruct the approximations at level 7 for each row
signal. Then, to compare the approximations with the original
signals, let us display two plots (see figure below). The first one
shows all the original signals and the second one shows all the
corresponding approximations at level 7.
A7_ROW = mdwtrec(decROW,'a',7);
subplot(2,1,1);
plot(X(:,:)','r');
title('Original Data');
axis tight
subplot(2,1,2);
plot(A7_ROW(:,:)','b');
axis tight
title('Corresponding approximations at level 7');

As it can be seen, the general shape is captured by the


approximations at level 7, but some interesting features are lost.
For example, the bumps at the beginning and at the end of the
signals disappeared.
Superimposed Signals and Approximations
To compare more closely the original signals with their
corresponding approximations at level 7, let us display two plots
(see figure below). The first one concerns the four first signals and
the second one the five last signals. Each of these plots represents
the original signals superimposed with their corresponding
approximation at level 7.
subplot(2,1,1);
idxDays = 1:4;
plot(X(idxDays,:)','r');hold on
plot(A7_ROW(idxDays,:)','b');

axis tight
title(['Days ' int2str(idxDays), ' - Signals and Approximations at
level 7']);
subplot(2,1,2);
idxDays = 31:35;
plot(X(idxDays,:)','r'); hold on
plot(A7_ROW(idxDays,:)','b');
axis tight
title(['Days ' int2str(idxDays), ' - Signals and Approximations at
level 7']);

As it can be seen, the approximation of the original signal is


visually accurate in terms of general shape.
Multisignal Denoising

To perform a more subtle simplification of the multisignal


preserving these bumps which are clearly attributable to the
electrical signal, let us denoise the multisignal.
The denoising procedure is performed using three steps:
1) Decomposition : Choose a wavelet and a level of
decomposition N, and then compute the wavelet decompositions of
the signals at level N.
2) Thresholding : For each level from 1 to N and for each signal, a
threshold is selected and thresholding is applied to the detail
coefficients.
3) Reconstruction : Compute wavelet reconstructions using the
original approximation coefficients of level N and the modified
detail coefficients of levels from 1 to N.
Let us choose now the level of decomposition N = 5 instead of N =
7 used previously.
dirDec = 'r';
% Direction of decomposition
level = 5;
% Level of decomposition
wname = 'sym4';
% Near symmetric wavelet
decROW = mdwtdec(dirDec,X,level,wname);
[XD,decDEN] = mswden('den',decROW,'sqtwolog','mln');
Residuals = X-XD;
subplot(3,1,1);
plot(X','r'); axis tight
title('Original Data: 35 days of electrical consumption')
subplot(3,1,2);
plot(XD','b'); axis tight
title('Denoised Data: 35 days of electrical consumption')
subplot(3,1,3);

plot(Residuals','k'); axis tight


title('Residuals')
xlabel('Minutes from 1 to 1440')

The quality of the results is good. The bumps at the beginning and
at the end of the signals are well recovered and, conversely, the
residuals look like a noise except for some remaining bumps due to
the signals. Furthermore, the magnitude of these remaining bumps
is of a small order.
Multisignal Compressing Row Signals
Like denoising, the compression procedure is performed using
three steps (see above).
The difference with the denoising procedure is found in step 2.
There are two compression approaches available:

The first one consists of taking the wavelet expansions of the


signals and keeping the largest absolute value coefficients. In
this case, you can set a global threshold, a compression
performance, or a relative square norm recovery
performance. Thus, only a single signal-dependent parameter
needs to be selected.
The second approach consists of applying visually
determined level-dependent thresholds.

To simplify the data representation and to make more efficient the


compression, let us go back to the decomposition at level 7 and
compress each row of the multisignal by applying a global
threshold leading to recover 99% of the energy.
dirDec = 'r';
% Direction of decomposition
level = 7;
% Level of decomposition
wname = 'sym4';
% Near symmetric wavelet
decROW = mdwtdec(dirDec,X,level,wname);
[XC,decCMP,THRESH] = mswcmp('cmp',decROW,'L2_perf',99);
subplot(3,1,1); plot(X','r'); axis tight
title('Original Data: 35 days of electrical consumption')
subplot(3,1,2); plot(XC','b'); axis tight
title('Compressed Data: 35 days of electrical consumption')
subplot(3,1,3); plot((X-XC)','k'); axis tight
title('Residuals')
xlabel('Minutes from 1 to 1440')

As it can be seen, the general shape is preserved while the local


irregularities are neglected. The residuals contain noise as well as
components due to the small scales essentially.
Compression Performance
Let us now compute the corresponding densities of nonzero
elements.
cfs = cat(2,[decCMP.cd{:},decCMP.ca]);
cfs = sparse(cfs);
perf = zeros(1,nbSIG);
for k =1:nbSIG
perf(k) = 100*nnz(cfs(k,:))/nbVAL;
end
figure('Color','w')
plot(perf,'r-*');

title('Percentages of nonzero coefficients for the 35 days')


xlabel('Signal indices');
ylabel('% of nonzero coefficients');

For each signal, the percentage of required coefficients to recover


99% of the energy lies between 1.25% and 1.75%. This illustrates
the spectacular capacity of wavelets to concentrate signal energy in
few coefficients.
Stats_TBX_Flag = isstatstbxinstalled;
if ~Stats_TBX_Flag
WarnStr = isstatstbxinstalled('msg');
uiwait(msgbox(WarnStr,...
'Using clustering tools','warn','modal'));
msg = {...
'Denoising, compression and clustering using wavelets are very
efficient'

'tools. The capacity of wavelet representations to concentrate


signal'
'energy in few coefficients is the key of efficiency.'
'In addition, clustering offers a convenient procedure to
summarize a'
'large set of signals using sparse wavelet representations.'
};
uiwait(msgbox(msg,...
'Using clustering tools','warn','modal'));
return
end
Clustering Row Signals
Let us now compare three different clustering of the 35 days. The
first one is based on the original multisignal, the second one on the
approximation coefficients at level 7 and the last one on the
denoised multisignal.
Using the GUI to inspect the dendrogram related to the clustering
process (not reported here), let us set to 3 the number of clusters.
Then, let us compute the structures P1 and P2 which contain
respectively the two first partitions and the third one.
P1 = mdwtcluster(decROW,'lst2clu',{'s','ca7'},'maxclust',3);
P2 = mdwtcluster(decDEN,'lst2clu',{'s'},'maxclust',3);
Clusters = [P1.IdxCLU P2.IdxCLU];
We can now test the equality of the three partitions.
EqualPART = isequal(max(diff(Clusters,[],2)),[0 0])
EqualPART =
1

So the three partitions are the same. Let us now plot and examine
the clusters.
figure('Color','w')
stem(Clusters,'filled','b:')
title('The three clusters of the original 35 days')
xlabel('Signal indices');
ylabel('Index of cluster');
set(gca,'XLim',[1 35],'YLim',[0.5 3.1],'YTick',1:3);

The first cluster (labelled 3) contains 25 mid-week days and the


two others (labelled 2 and 1) contain 5 saturdays and 5 sundays
respectively. This illustrates again the periodicity of the underlying
time series and the three different general shapes seen in the two
first plots displayed at the beginning of this example.

Let us now display the original signals and the corresponding


approximation coefficients used to obtain two of the three
partitions.
CA7 = mdwtrec(decROW,'ca');
IdxInCluster = cell(1,3);
for k=1:3
IdxInCluster{k} = find(P2.IdxCLU==k);
end
figure('Color','w','Units','normalized','Position',[0.2 0.2 0.6 0.6])
for k = 1:3
idxK = IdxInCluster{k};
subplot(2,3,k);
plot(X(idxK,:)','r'); axis tight
set(gca,'XTick',[200 800 1400]);
if k==2
title('Original signals')
end
xlabel(['Cluster: ' int2str(k) ' (' int2str(length(idxK)) ')']);
subplot(2,3,k+3);
plot(CA7(idxK,:)','b'); axis tight
if k==2
title('Coefficients of approximations at level 7')
end
xlabel(['Cluster: ' int2str(k) ' (' int2str(length(idxK)) ')']);
end

The same partitions are obtained from the original signals (1440
samples for each signal) and from the coefficients of
approximations at level 7 (18 samples for each signal). This
illustrates that using less than 2% of the coefficients is enough to
get the same clustering partitions of the 35 days.
Summary

Denoising, compression and clustering using wavelets are very


efficient tools. The capacity of wavelet representations to
concentrate signal energy in few coefficients is the key of
efficiency. In addition, clustering offers a convenient procedure to
summarize a large set of signals using sparse wavelet
representations.
Was this topic helpful?
Try MATLAB, Simulink, and Other Products
Get trial now

Join the conversation

Preventing Piracy
Privacy Policy
Trademarks
Patents
Site Help

1994-2012 The MathWorks, Inc.


Detecting Discontinuities and Breakdown Points
Signals with very rapid evolutions such as transient signals in
dynamic systems may undergo abrupt changes such as a jump, or a
sharp change in the first or second derivative. Fourier analysis is
usually not able to detect those events. The purpose of this
example is to show how analysis by wavelets can detect the exact
instant when a signal changes and also the type (a rupture of the
signal, or an abrupt change in its first or second derivative) and

amplitude of the change. In image processing, one of the major


application is edge detection, which also involves detecting abrupt
changes.
Frequency Breakdown
Short wavelets are often more effective than long ones in detecting
a signal rupture. Therefore, to identify a signal discontinuity, we
will use the haar wavelet. The discontinuous signal consists of a
slow sine wave abruptly followed by a medium sine wave.
load freqbrk
x = freqbrk;
Compute the multilevel 1-D wavelet decomposition at level 1
level = 1;
[c,l] = wavedec(x,level,'haar');
Extract the detail coefficients at level 1 from the wavelet
decomposition and visualize the result
d1 = detcoef(c,l,level);
subplot(211),plot(x)
subplot(212),plot(interpft(d1,2*length(d1)));ylabel('d1')

The first-level details (d1) show the discontinuity most clearly,


because the rupture contains the high-frequency part. The
discontinuity is localized very precisely around time = 500.
The presence of noise, which is after all a fairly common situation
in signal processing, makes identification of discontinuities more
complicated. If the first levels of the decomposition can be used to
eliminate a large part of the noise, the rupture is sometimes visible
at deeper levels in the decomposition.
Second Derivation Breakdown
The purpose of this example is to show how analysis by wavelets
can detect a discontinuity in one of a signal's derivatives. The
signal, while apparently a single smooth curve, is actually
composed of two separate exponentials.
load scddvbrk;

x = scddvbrk;
level = 2;
[c,l] = wavedec(x,level,'db4');
[d1 d2] = detcoef(c,l,1:level);
subplot(311),plot(x),xlim([400 600])
subplot(312),d1up(1:2:1008)=d1;plot(d1up);ylabel('d1'),xlim([400
600])
subplot(313),d2up(1:4:1020)=d2;plot(d2up);ylabel('d2'),xlim([400
600])

We have zoomed in on the middle part of the signal to show more


clearly what happens around time = 500. The details are high only
in the middle of the signal and are negligible elsewhere. This
suggests the presence of high-frequency information -- a sudden
change or discontinuity -- around time = 500.

Note that to detect a singularity, the selected wavelet must be


sufficiently regular, which implies a longer filter impulse response.
Regularity can be an important criterion in selecting a wavelet. We
have chosen to use db4, which is sufficiently regular for this
analysis. Had we chosen the haar wavelet, the discontinuity would
not have been detected. If you try repeating this analysis using haar
at level two, you'll notice that the details are equal to zero at time =
500.
Edge Detection
For images, a two-dimensional DWT leads to a decomposition of
approximation coefficients at level j in four components: the
approximation at level j+1, and the details in three orientations
(horizontal, vertical, and diagonal).
load tartan;
level = 1;
[c,s] = wavedec2(X,level,'coif2');
[chd1,cvd1,cdd1] = detcoef2('all',c,s,level);
figure('Color','white'), image(X), colormap(map)
title('Original Image')
figure('Color','white'), image(chd1),colormap(map)
title('Horizontal Edges')

figure('Color','white'), image(cvd1), colormap(map)


title('Vertical Edges')
figure('Color','white'), image(cdd1),colormap(map)
title('Diagonal Edges')

Two-Dimensional True Compression


Starting from a given image, the goal of true compression is to
minimize the number of bits needed to represent it, while storing
information of acceptable quality. Wavelets contribute to effective
solutions for this problem. The complete chain of compression
includes iterative phases of quantization, coding, and decoding, in
addition to the wavelet processing itself.
The purpose of this example is to show how to decompose,
compress, and decompress a grayscale or truecolor image using
various compression methods. To illustrate these capabilities, we
consider a grayscale image of a mask and a truecolor image of
peppers.
Compression by Global Thresholding and Huffman Encoding
First we load and display the mask grayscale image.

load mask
image(X)
axis square
colormap(pink(255))
title('Original Image: mask')

A measure of achieved compression is given by the compression


ratio (CR) and the Bit-Per-Pixel (BPP) ratio. CR and BPP
represent equivalent information. CR indicates that the compressed
image is stored using CR % of the initial storage size while BPP is
the number of bits used to store one pixel of the image. For a
grayscale image the initial BPP is 8. For a truecolor image the
initial BPP is 24, because 8 bits are used to encode each of the
three colors (RGB color space).

The challenge of compression methods is to find the best


compromise between a low compression ratio and a good
perceptual result.
We begin with a simple method of cascading global coefficients
thresholding and Huffman encoding. We use the default wavelet
bior4.4 and the default level, which is the maximum possible level
(see the WMAXLEV function) divided by 2. The desired BPP is
set to 0.5 and the compressed image is stored in the file named
mask.wtc.
meth = 'gbl_mmc_h'; % Method name
option = 'c';
% 'c' stands for compression
[CR,BPP] = wcompress(option,X,'mask.wtc',meth,'BPP',0.5)
CR =
6.6925
BPP =
0.5354
The achieved Bit-Per-Pixel ratio is actually about 0.53 (closed to
the desired one of 0.5) for a compression ratio of 6.7%.
Uncompression
Now we decompress the image retrieved from the file mask.wtc
and compare it to the original image.
option = 'u'; % 'u' stands for uncompression
Xc = wcompress(option,'mask.wtc');
colormap(pink(255))
subplot(1,2,1); image(X);

axis square;
title('Original Image')
subplot(1,2,2); image(Xc);
axis square;
title('Compressed Image')
xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')], ...
['BPP: ' num2str(BPP,'%3.2f')]})

The result is satisfactory, but a better compromise between


compression ratio and visual quality can be obtained using more
sophisticated true compression methods, which involve tighter
thresholding and quantization steps.
Compression by Progressive Methods
We now illustrate the use of progressive methods of compression,
starting with the EZW algorithm using the Haar wavelet. The key

parameter is the number of loops; increasing it leads to better


recovery, but a worse compression ratio.
meth = 'ezw'; % Method name
wname = 'haar'; % Wavelet name
nbloop = 6;
% Number of loops
[CR,BPP] = wcompress('c',X,'mask.wtc',meth,'maxloop', nbloop,
...
'wname','haar');
Xc = wcompress('u','mask.wtc');
colormap(pink(255))
subplot(1,2,1); image(X);
axis square;
title('Original Image')
subplot(1,2,2); image(Xc);
axis square;
title('Compressed Image - 6 steps')
xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')], ...
['BPP: ' num2str(BPP,'%3.2f')]})

Here, using only 6 steps produces a very coarse decompressed


image. Now we examine a slightly better result using 9 steps and
finally a satisfactory result using 12 steps.
[CR,BPP] =
wcompress('c',X,'mask.wtc',meth,'maxloop',9,'wname','haar');
Xc = wcompress('u','mask.wtc');
colormap(pink(255))
subplot(1,2,1); image(Xc);
axis square;
title('Compressed Image - 9 steps')
xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')],...
['BPP: ' num2str(BPP,'%3.2f')]})
[CR,BPP] =
wcompress('c',X,'mask.wtc',meth,'maxloop',12,'wname','haar');
Xc = wcompress('u','mask.wtc');

subplot(1,2,2); image(Xc);
axis square;
title('Compressed Image - 12 steps')
xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')], ...
['BPP: ' num2str(BPP,'%3.2f')]})

The final BPP ratio is approximately 0.92 when using 12 steps.


Now we try to improve the results by using the wavelet bior4.4
instead of haar and looking at loops of 12 and 11 steps.
[CR,BPP] = wcompress('c',X,'mask.wtc','ezw','maxloop',12, ...
'wname','bior4.4');
Xc = wcompress('u','mask.wtc');
colormap(pink(255))
subplot(1,2,1); image(Xc);
axis square;
title('Compressed Image - 12 steps - bior4.4')

xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')], ...


['BPP: ' num2str(BPP,'%3.2f')]})
[CR,BPP] = wcompress('c',X,'mask.wtc','ezw','maxloop',11, ...
'wname','bior4.4');
Xc = wcompress('u','mask.wtc');
subplot(1,2,2); image(Xc);
axis square;
title('Compressed Image - 11 steps - bior4.4')
xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')], ...
['BPP: ' num2str(BPP,'%3.2f')]})

For the eleventh loop, we see that the result can be considered
satisfactory, and the obtained BPP ratio is approximately 0.35. By
using a more recent method, SPIHT (Set Partitioning in
Hierarchical Trees), the BPP can be improved further.

[CR,BPP] = wcompress('c',X,'mask.wtc','spiht','maxloop',12, ...


'wname','bior4.4');
Xc = wcompress('u','mask.wtc');
colormap(pink(255))
subplot(1,2,1); image(X);
axis square;
title('Original Image')
subplot(1,2,2); image(Xc);
axis square;
title('Compressed Image - 12 steps - bior4.4')
xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')], ...
['BPP: ' num2str(BPP,'%3.2f')]})

The final compression ratio (2.8%) and Bit-Per-Pixel ratio (0.23)


are very satisfactory. Recall that the CR means that the compressed
image is stored using only 2.8% of the initial storage size.

Handling Truecolor Images


Finally, we illustrate how to compress the wpeppers.jpg truecolor
image. Truecolor images can be compressed using the same
scheme as grayscale images by applying the same strategies to
each of the three color components.
The progressive compression method used is SPIHT (Set
Partitioning in Hierarchical Trees) and the number of encoding
loops is set to 12.
X = imread('wpeppers.jpg');
[CR,BPP] = wcompress('c',X,'wpeppers.wtc','spiht','maxloop',12);
Xc = wcompress('u','wpeppers.wtc');
colormap(pink(255))
subplot(1,2,1); image(X);
axis square;
title('Original Image')
subplot(1,2,2); image(Xc);
axis square;
title('Compressed Image - 12 steps - bior4.4')
xlabel({['Compression Ratio: ' num2str(CR,'%1.2f %%')], ...
['BPP: ' num2str(BPP,'%3.2f')]})
delete('wpeppers.wtc')

The compression ratio (1.65%) and the Bit-Per-Pixel ratio (0.4) are
very satisfactory while maintaining a good visual perception.
More about True Compression of Images
For more information about True Compression of images,
including some theory and examples, see the following reference:
Misiti, M., Y. Misiti, G. Oppenheim, J.-M. Poggi (2007),
"Wavelets and their applications", ISTE DSP Series.
Was this topic helpful?
Try MATLAB, Simulink, and Other Products
Get trial now

Join the conversation

Preventing Piracy
Privacy Policy
Trademarks
Patents
Site Help

1994-2012 The MathWorks, Inc.

You might also like