首页 > 解决方案 > 使用数组在matlab中实现huffmandict()函数

问题描述

我想在 Matlab 中实现 huffmandict() 函数。我已经编写了一个代码,在其中创建了一个包含所有概率的数组。每次我添加 2 last probabilities 时,我都会通过在正确位置的下一行添加新的总和概率来更新我的数组。我也有一个只有总和的数组。问题是我不知道如何继续分配'0'和'1'。任何想法?这是我的代码:

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

标签: matlabhuffman-code

解决方案


推荐阅读