Implement huffmandict() function in matlab using arrays

时间:2018-12-19 11:22:01

标签: matlab huffman-code

I would like to implement the huffmandict() function in Matlab. I have already written a code in which I create an array with all the probabilities. Each time I add the 2 last probabilities , I update my array by adding the new sum probability at the next row in the right place. I also have an array with the sums only. The problem is I don't know how to continue to assign '0' and '1'. Any idea? This is my code:

function code_words = my_huffmandict_func(init_symbols,probs) 

my_symbol_array = [];
my_symbol_array = init_symbols;
my_probs = [];
my_probs = probs;

if length(my_symbol_array)~=length(my_probs)
 error('Number of symbols and number of probabilities are not the same.');
end

for i=1:length(my_probs) %sorting the probabilities in descending order and 
change the sequence of the symbols
for j=1:length(my_probs)
    if (my_probs(i)> my_probs(j))
        temp1=my_probs(i);
        temp2=my_symbol_array(i);
        my_probs(i)= my_probs(j);
        my_symbol_array(i)= my_symbol_array(j);
        my_probs(j)= temp1;
        my_symbol_array(j)= temp2;
    end
 end
end

my_sum_array = [];
k=1;
init_lengthpr = length(my_probs);
all_occured_probs = [];
all_occured_probs(1,:) = my_probs;

while length(my_probs)>2 %we need this while loop as long as there are more 
than 2 symbols left
my_temp_sum = my_probs(length(my_probs)) + my_probs(length(my_probs-1)); %we add the the possibilities of the two less possible outputs
my_sum_array = [my_sum_array,my_temp_sum]; %in this array we keep all the sums that occured
my_probs = [my_probs(1:length(my_probs)-2), my_temp_sum];%we update the possibilities' array
my_probs = sort(my_probs,'descend'); %we sort the array again
k=k+1;
all_occured_probs(k,:) = [my_probs,zeros(1,init_lengthpr-length(my_probs))];

end

end

0 个答案:

没有答案