信息论Matlab仿真——哈夫曼编码

《信息论与编码》第五章——哈夫曼编码

%@author Zhang
%@copyright Zhang
%@release 2021.06.16

W = [0.05,0.29,0.07,0.08,0.14,0.23,0.03,0.11];

%得到哈夫曼编码表
n = size(W,2);%信源个数
m = 2*n - 1;%节点个数
HT = zeros(m,5);%生成m行5列的矩阵存放信息
HT(1:m,1) = 1:m;%第一列存放序号
HT(1:n,2) = W';%第二列的前n行存放信源概率
for i = n+1:m
    [a,b] = find(HT(1:i-1,3) == 0);%寻找前i-1行没有确定父节点的节点
    X1 = HT(a,2);%将寻找到的节点的概率给X1
    X2 = sort(X1);%将X1按升序排列
    P1 = find(X1 == X2(1));%找到最小的概率
    P2 = find(X1 == X2(2));%找到第二小的概率
    %判断两个概率的类型
    if length(P1)>1        %最小的概率为两个相同值
        S1 = a(P1(1));
        S2 = a(P1(2));
    elseif length(P2)>1    %第二小的概率为两个相同的值
        S1 = a(P1);
        S2 = a(P2(1));
    else
        S1 = a(P1);
        S2 = a(P2);
    end
    HT(S1,3) = i;%将该节点的序号存入其左子节点的父节点位置
    HT(S2,3) = i;%将该节点的序号存入其右子节点的父节点位置
    HT(i,4) = S1;%将该节点的左子节点序号存入其左子节点位置
    HT(i,5) = S2;%将该节点的右子节点序号存入其右子节点位置
    HT(i,2) = HT(S1,2) + HT(S2,2);%将左右子节点的概率之和存入该节点的概率
end
HT1 = HT;

%得到哈夫曼树
p = m;
cdlen = 0;
HT((1:m),2) = 0;
while(p)
    if HT(p,2) == 0
        HT(p,2) = 1;
        if HT(p,4) ~= 0
            p = HT(p,4);
            cd(cdlen+1) = '0';
            cdlen = cdlen + 1;
        elseif HT(p,5) == 0
            HC{p} = cd;
        end
    elseif HT(p,2) == 1
        HT(p,2) = 2;
        if HT(p,5) ~= 0
            p = HT(p,5);
            cd(cdlen + 1) = '1';
            cdlen = cdlen + 1;
        end
    else
        HT(p,2) = 0;
        p = HT(p,3);
        if length(cd) > 1
            cd(end) = [];
        end
        cdlen = cdlen - 1;
    end
end
disp('哈夫曼编码表(序号-概率-父节点序号-左子序号-右子序号)');
disp(HT1);
disp('哈夫曼树(序号-flag-父节点序号-左子序号-右子序号)');
disp(HT);

 

上一篇:智慧水务 | 大坝水利可视化管理,综合态势一屏掌握


下一篇:ConvertAll与Hashtable用法