This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.


Huffman encoder


comp = huffmanenco(sig,dict)


comp = huffmanenco(sig,dict) encodes the signal sig using the Huffman codes described by the code dictionary dict. The argument sig can have the form of a numeric vector, numeric cell array, or alphanumeric cell array. If sig is a cell array, it must be either a row or a column. dict is an N-by-2 cell array, where N is the number of distinct possible symbols to be encoded. The first column of dict represents the distinct symbols and the second column represents the corresponding codewords. Each codeword is represented as a numeric row vector, and no codeword in dict can be the prefix of any other codeword in dict. You can generate dict using the huffmandict function.


collapse all

Create unique symbols, and assign probabilities of occurrence to them.

symbols = 1:6;
p = [.5 .125 .125 .125 .0625 .0625];

Create a Huffman dictionary based on the symbols and their probabilities.

dict = huffmandict(symbols,p);

Generate a vector of random symbols.

sig = randsrc(100,1,[symbols; p]);

Encode the random symbols.

comp = huffmanenco(sig,dict);

Decode the data. Verify that the decoded data matches the original data.

dsig = huffmandeco(comp,dict);
ans =



Convert the original signal to binary, and determine its length.

binarySig = de2bi(sig);
seqLen = numel(binarySig)
seqLen =


Convert the Huffman encoded signal and determine its length.

binaryComp = de2bi(comp);
encodedLen = numel(binaryComp)
encodedLen =


The Huffman encoded data required 224 bits, which is a 25% savings over the uncoded data.

More About


[1] Sayood, Khalid, Introduction to Data Compression, San Francisco, Morgan Kaufmann, 2000.

Introduced before R2006a

Was this topic helpful?