MATLAB Code for Quantization of discrete analog signals.
% Sampling and Quantization
b=4; % Number of bits.
N=120; % Number of samples in final signal.
n=0:(N-1);
x=sin(2*pi*n/N);
%x=sawtooth(2*pi*n/N);
%x=randn(1,N);%Random Signal
%x=x/max(abs(x));
% Signal is restricted to between -1 and +1.
x(x>=1)=(1-eps);
x(x<-1)=-1;
% Quantize a signal to “b” bits.
xq=floor((x+1)*2^(b-1));
xq=xq/(2^(b-1)); % Signal is from 0 to 2 (quantized)
xq=xq-(2^(b)-1)/2^(b); % Shift signal down (rounding)
xe=x-xq; % Quantization 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 ‘,b,2^b));
hold off


Thank me later and dont forget to follow