matlab哈夫曼编解码代码
时间: 2023-10-01 11:08:56 浏览: 109
以下是Matlab实现的哈夫曼编解码代码:
%% 哈夫曼编码函数
function [code, dict] = huffman_encode(symbol, prob)
% 统计符号个数
n = length(prob);
% 建立哈夫曼树
tree = build_huffman_tree(prob);
% 生成哈夫曼编码字典
dict = get_huffman_dict(tree);
% 生成哈夫曼编码
code = cell(n, 1);
for k = 1:n
code{k} = dict(symbol(k));
end
%% 哈夫曼解码函数
function symbol = huffman_decode(code, dict)
% 生成反向哈夫曼编码字典
rev_dict = cell(length(dict), 1);
for k = 1:length(dict)
rev_dict{dict{k}} = k;
end
% 解码
symbol = cell(length(code), 1);
for k = 1:length(code)
symbol{k} = rev_dict{code{k}};
end
%% 构建哈夫曼树函数
function tree = build_huffman_tree(prob)
% 初始化叶子节点
n = length(prob);
tree = cell(n, 1);
for k = 1:n
tree{k} = struct('symbol', k, 'prob', prob(k), 'parent', [], 'left', [], 'right', []);
end
% 构建哈夫曼树
while length(tree) > 1
% 找到概率最小的两个节点
[~, idx] = sort([tree{:}.prob]);
idx = idx(1:2);
% 合并两个节点
parent = struct('symbol', [], 'prob', tree{idx(1)}.prob + tree{idx(2)}.prob, 'parent', [], 'left', tree{idx(1)}, 'right', tree{idx(2)});
tree{idx(1)}.parent = parent;
tree{idx(2)}.parent = parent;
% 删除已合并的节点
tree(idx(2)) = [];
tree(idx(1)) = {parent};
end
%% 生成哈夫曼编码字典函数
function dict = get_huffman_dict(tree)
% 递归生成哈夫曼编码字典
dict = cell(length(tree), 1);
for k = 1:length(tree)
node = tree{k};
code = '';
while ~isempty(node.parent)
if node == node.parent.left
code = ['0' code];
else
code = ['1' code];
end
node = node.parent;
end
dict{k} = code;
end
阅读全文