I want Huffman coding
23 次查看(过去 30 天)
显示 更早的评论
(Huffman coding example, codex.m) Open the code codex.m using the editor. Note
“m” parameter which indicates the number of simulated symbols in array “x”.
1. Determine the size of encoded binary sequence in array “cx”. Calculate the compression
ratio in comparison with no-encoding scenario, when each symbol is encoded by two
bits.
2. Compute the number of bits per symbol, i.e. the ratio of lengths for arrays “cx” and “x”.
Compare with the theoretical number of bits per symbol as in notes example on pages
10-11 (Intro-Source-Coding)
%codex.m example of Huffman coding and decoding
clear
m=1000; % number of code words
% codex.m step 1: generate a 4-PAM sequence
% with probabilities 0.5, 0.25, 0.125, and 0.125
for i=1:m
r=rand;
if r<0.5, x(i)=+1; end
if (r>=0.5) & (r<0.75), x(i)=-1; end
if (r>=0.75) & (r<0.875), x(i)=+3; end
if r>=0.875, x(i)=-3; end
end
% codex.m step 2: encode the sequence using Huffman code
j=1;
for i=1:m
if x(i)==+1, cx(j:j)=[1]; j=j+1; end
if x(i)==-1, cx(j:j+1)=[0,1]; j=j+2; end
if x(i)==+3, cx(j:j+2)=[0,0,1]; j=j+3; end
if x(i)==-3, cx(j:j+2)=[0,0,0]; j=j+3; end
end
% codex.m step 3: decode the variable length sequence
j=1; i=1;
while i<=length(cx)
if cx(i:i)==[1], y(j)=+1; i=i+1; j=j+1;
elseif cx(i:i+1)==[0,1], y(j)=-1; i=i+2; j=j+1;
elseif cx(i:i+2)==[0,0,1], y(j)=+3; i=i+3; j=j+1;
elseif cx(i:i+2)==[0,0,0], y(j)=-3; i=i+3; j=j+1; end
end
err=sum(abs(x-y))
回答(1 个)
Sulaymon Eshkabilov
2022-11-27
Have you visited to this doc: Encode sequence of symbols by Huffman encoding - MATLAB huffmanenco (mathworks.com)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!