matlab - 使用数组在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
解决方案
推荐阅读
- java - 在异步中显示敬酒
- node.js - 将 JSON 导入 Firebase 得到 Invalid or Unexpected Token 错误
- python - difflib - 使用 ndiff() 忽略空格差异?
- c# - OrganizationWebProxyClient - 端点 = 地址 = 错误 CS0103:名称“_address”在当前上下文中不存在,ClientCredentials
- reactjs - 使用 React/redux 添加/删除项目后刷新项目列表的方法
- r - .r 版本的目的是什么
- python - 如何将字符串分成大小相等的部分?
- ruby - 如何在 Ruby 2.7+ IRB 多行编辑模式下添加新行?
- c++ - 为什么要获取像 `&myArray[i]` 这样的数组元素的地址?二维数组
- algorithm - N = 25 皇后问题。使用香草爬山算法