You are on page 1of 2

huffman2

function code=huffman2(prob)
%% Function to generate huffman dictionary from a list of probabilities
%% Normalisation the probabilities is done whwn anly frequency of occurance is
provided
prob = prob/sum(prob);
for index = 1:length(prob)
% assignment of an empty codeword for each probability
codewords{index} = [];
% Create a set containing only this codeword
set_contents{index} = index;
% Store the probability associated with this set
set_prob(index) = prob(index);
end
% Formation of Huffman Tree and assignment of codewords
while length(set_contents) > 1
% sorting of probability array
[temp, sorted_indices] = sort(set_prob);
% lowest probability index
zero_set = set_contents{sorted_indices(1)};
% Get that probability
zero_prob = set_prob(sorted_indices(1));
% For each codeword in the set a zero is appended
for codeword_index = 1:length(zero_set)
codewords{zero_set(codeword_index)} = [0,
codewords{zero_set(codeword_index)}];
end
%second lowest probability index
one_set = set_contents{sorted_indices(2)};
% Get that probability
one_prob = set_prob(sorted_indices(2));
% For each codeword in the set a one is appended
for codeword_index = 1:length(one_set)
codewords{one_set(codeword_index)} = [1,
codewords{one_set(codeword_index)}];
end

% lowest two probability indices are removed


set_contents(sorted_indices(1:2)) = [];
% merged into single set i.e a branch of the tree
set_contents{length(set_contents)+1} = [zero_set, one_set];
% Remove the two lowest probabilities...
set_prob(sorted_indices(1:2)) = [];
% ...and give their sum to the new set
set_prob(length(set_prob)+1) = zero_prob + one_prob;
end
%%disp('-------------------------------------------------------------------------');
%%disp('The symbols, their probabilities and the allocated Huffman codewords are:');
% For each codeword...
for index = 1:length(codewords)
%% % ...display its bits in reverse order
code{index}=codewords{index};
Page 1

%%disp([num2str(index), '
',num2str(codewords{index})]);
end

huffman2
', num2str(prob(index)),'

%%disp(['The symbol entropy is:


%%disp(['The average Huffman codeword length is:
%%disp(['The Huffman coding rate is:

Page 2

',num2str(entropy)]);
',num2str(av_length)]);
',num2str(entropy/av_length)]);

You might also like