Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 7

clc;

close all;
clear all;
Fs = 8000;
t = (0:1/Fs:(1/ 100)*3);
s = 1*cos(2*pi*0*100*t + 0) + 2*cos(2*pi*2*100*t + pi/2) + 3*cos(2*pi*9*100*t
+ (3*pi)/2);
MU = 2; % MU: la he so nen
amax = max(abs(s)); % tim so on nhat trong vector s
[y] = compand(s,MU,amax,'mu/compressor'); % nen theo luat muji
[code,saukhi_pcm,sqnr] = pcm(s,2^8); % luong tu hoa pcm
[saukhigiainen] = compand(saukhi_pcm,MU,amax,'mu/expander'); % giai nen theo
luat muji
figure(1);
plot(t,s);
grid on;
title('Tin hieu goc');
xlabel('t');
ylabel('A');
figure(2)
plot(t,s)
hold on;
stairs(t,saukhi_pcm);
grid on;
xlabel('t');
ylabel('A');
title('Tin hieu goc va tin hieu luong tu hoa');
legend('Tin hieu goc','Tin hieu luong tu hoa');
figure(3)
plot(t,s,t,saukhigiainen);
xlabel('t');
ylabel('A');
grid on;
title('Tin hieu goc va tin hieu sau khoi phuc');
legend('Tin hieu goc','Tin hieu sau khoi phuc');
Ns = length(s);
F = (-Ns/2:Ns/2-1)/(Ns*(t(2) - t(1))); % tao mien tan so f theo mien thoi
gian t
figure(4)
Pf_s = spectrum(s);
semilogy(F,Pf_s);
xlabel('f');
ylabel('PSD');
grid on;
title('Pho tin hieu goc');
figure(5)
pho_pcm = spectrum(saukhi_pcm);
semilogy(F,pho_pcm);
xlabel('f');
ylabel('PSD');
grid on;
title('Pho tin hieu sau khi luong tu hoa');
figure(6)
pho_khoiphuc = spectrum(saukhigiainen);
semilogy(F,pho_khoiphuc);
xlabel('f');
ylabel('PSD');
grid on;
title('Pho tin hieu sau khi khoi phuc');
figure(7)
plot(t,s,t,y);
xlabel('t');
ylabel('A');
title('Tin hieu truoc va sau bo nen')
legend('Tin hieu truoc bo nen','Tin hieu sau bo nen');
grid on;
Hàm pcm.m

function [code,xq,sqnr] = pcm(x,M)


% x = input sequence
% M = number of quantization levels
% code = the encoded output
% xq = quantized sequence before encoding
% sqnr = signal to quantization noise ratio in dB
Nb = log2(M); % S? bit trên m?i t? mã
Amax = max(abs(x));
delta = 2*Amax/(M-1);
Mq = -Amax:delta:Amax;
Ml = 0:M-1;
xq = zeros(size(x));
xcode = xq;
for k = 1:M
ind = find(x > Mq(k)-delta/2 & x <= Mq(k)+delta/2);
xq(ind) = Mq(k);
xcode(ind) = Ml(k);
end
sqnr = 20*log10(norm(x)/norm(x-xq)); % Tính t? s? trên nhi?u l??ng t?
code = de2bi(xcode,Nb,'left-msb'); % Chuy?n ??i sang t? mã nh? phân

hàm spectrum.m

function [ Pf ] = spectrum( s )
% Tao dang pho
% s: Tin hieu dau vao
% Pf: tin hieu sau khi duoc fft
len = length(s);
Pf = fft(s,len);
Pf = fftshift(Pf)/len;
Pf = abs(Pf).^2;
end

You might also like