%霍夫曼编码clc;clear;u=[0.4,0.2,0.1,0.1,0.1,0.05,0.05];[u,k]=sort(u);k=fliplr(k);a=fliplr(u);[m,n]=size(u);B=zeros(n,n-1);%空的编码表(矩阵)fori=1:nB(i,1)=a(i);endforj=1:n-2tmp=B(n-j+1,j)+B(n-j,j);a(n-j+1)=0;a(n-j)=tmp;a=fliplr(sort(a));fori=1:nB(i,j+1)=a(i);end%查找合并后概率位置r=find(a==tmp);B(n,j+1)=r(end);%必须要加上end,保证排序endindex=cell(n,n-1);index{1,n-1}='0';index{2,n-1}='1';t=2;fort=2:n-1%给倒数第t列元素编码index{t,n-t}=[index{B(n,n-t+1),n-t+1},'0'];index{t+1,n-t}=[index{B(n,n-t+1),n-t+1},'1'];if(B(n,n-t+1)==1)forj=1:t-1index{j,n-t}=index{j+1,n-t+1};endelseforj=1:B(n,n-t+1)-1index{j,n-t}=index{j,n-t+1};endforj=B(n,n-t+1):t-1index{j,n-t}=index{j+1,n-t+1};endendendfori=1:nlen(i)=length(index{i,1});endu=fliplr(u);avlen=sum(len.*u)%平均码长H=sum(-u.*log2(u))P=H/avlen