Anda di halaman 1dari 3

DSP for Engineering Applications

MATLAB Workshop

Experiment1. Sampling and Quantization Using MATLAB


The aim of this lab session is to study how to use MATLAB to implement the sampling and quantization in DSP. Equipments: PCs with Windows operating systems and Matlab program

Exercises 1: Sampling and Quantization MATLAB


Test the following m code %Quantize a signal to n bits. %and +1. This code assumes the signal is between -1

n=8; %Number of bits; m=120; %Number of samples; x=sawtooth(2*pi*(0:(m-1))/m); %signal between -1 and 1. %Trying "sin()" instead of "sawtooth" %results in more interesting error(to the %extent that error is interesting). x(find(x>=1))=(1-eps); %Make signal from -1 to just less than 1. xq=floor((x+1)*2^(n-1)); %Signal is one of 2^n int values (0 to 2^n-1) xq=xq/(2^(n-1)); %Signal is from 0 to 2 (quantized) xq=xq-(2^(n)-1)/2^(n); %Shift signal down (rounding) xe=x-xq; %Error

stem(x,'b'); hold on; stem(xq,'r'); hold on; stem(xe,'g'); legend('exact','quantized','error','Location','Southeast') title(sprintf('Signal, Quantized signal and Error for %g bits, %g quantization levels',n,2^n)); hold off

Change the variable n and m to see the change of the output. Change the input x to different signal like sinusoidal or exponential and check the results.

References:
1. http://www.mathworks.co.uk

Questions:
Change the ex 1 code to create a quantizer function that access a zero-mean input and produce an integer output after n-bit quantization.

DFT Implementation Using MATLAB Dr Z Zhao 2008

Page 1

DSP for Engineering Applications

MATLAB Workshop

Experiment1. Sampling and Quantization Using MATLAB


The aim of this lab session is to study how to use MATLAB to implement the sampling and quantization in DSP. Equipments: PCs with Windows operating systems and Matlab program

Exercises 1:- Sampling and Quantization MATLAB


MATLAB Code for Sampling and Quantization of Analog Signal:
Test the following m code clc; clear all; close all; % Analog Signal f=50; t=0:1/100/f:1/f; x=sin(2*pi*f*t); subplot(311); plot(t,x); title('Analog Signal x(t)') xlabel('t'); ylabel('x(t)'); % Sampling n=50; % No. of Samples xs = sin(2*pi*(0:n)/n); subplot(312); stem((0:n),xs); title('Sampled Signal x[n]') xlabel('n'); ylabel('x[n]'); % Quantizing B=3; xs(xs>=1)=(1-eps); xq=floor((xs+1)*2^(B-1)); xq=xq/(2^(B-1)); xq=xq-(2^(B)-1)/2^(B); subplot(313); stem((0:n),xq); title('Quantized Signal xq[n]') xlabel('n'); ylabel('xq[n]');
DFT Implementation Using MATLAB Dr Z Zhao 2008 Page 2

DSP for Engineering Applications


MATLAB Workshop

Change the variable n and m to see the change of the output. Change the input x to different signal like sinusoidal or exponential and check the results.

DFT Implementation Using MATLAB Dr Z Zhao 2008

Page 3