huffman.m:
%huffman编码的递归实现。
%输入:input:第一列为值,第二列为各个值的概率。
% codein,输入[]即可,没用,作递归时用到。
%输出:output:排序后的input。
% code:对应p每行的huffman编码。
% key:没用,设为~即可,作递归时用到。
%参看测试代码huffmanTEST.m。
function [ output, code, key ] = huffman( input, codein )
[sp,~] = size(input);
if sp==1
code = codein;
key = 1;
output = input;
return;
end
[~,index] = sort(input(:,2),'descend');
output = input(index,:);
key = find(index==sp);
if ~iscell(codein)
codein = cell(sp,1);
else
codeintemp = codein;
for t = 1:sp
codein{t} = codeintemp{index(t)};
end
end
ptemp = output;
ptemp(sp-1,:) = ptemp(sp-1,:)+ptemp(sp,:);
[~, codetemp, keytemp] = huffman(ptemp(1:sp-1,:),codein);
code = codetemp;
code(keytemp) = [];
code{sp-1}=[codetemp{keytemp},'0'];
code{sp}=[codetemp{keytemp},'1'];
end
huffmanTest.m:
clear;
close all;
clc;
input = rand(150,2);
input = input / sum(input(:,2))
[output,code,~] = huffman(input,[])