计算信源熵的MATLAB 源程序
function H=entropy(P,r)
if (length(find(P
error('Not a prob.vector,negative component');
end
if(abs(sum(P)-1)>10e-10)
error('Not a prob.vector,component do not add up to 1');
end
H=(sum(-P.*log2(P)))/(log2(r)+eps);
香农编码的MATLAB 源程序
function [s,L,q]=shannon(p)
%if(length(find(p
% error('Not a prob.vector,negative component');
%end
%if(abs(sum(p)-1)>10e-10)
% error('Not a prob.vector,component do not add up to 1')
%end
n=length(p);
x=1:n;
[p,x]=array(p,x);
l=ceil(-log2(p));
P(1)=0;
n=length(p);
for i=2:n
P(i)=P(i-1)+p(i-1);
end
for i=1:n
for j=1:l(i)
temp(i,j)=floor(P(i)*2);
P(i)=P(i)*2-temp(i,j);
end
end
s=[];
for i=1:n
for j=1:l(i)
t=temp(i,j);
% if(temp(i,j)==0)
% W(i,j)=48;
s=[s num2str(t)];
%else
%W(i,j)=49;
% end
end
s=[s ' '];
end
L=sum(p.*l);
H=entropy(p,2);
q=H/L;
for i=1:n
B{i}=i;
end
s0='很好!输入正确,编码结果如下:';
s1='Shannon 编码所得码字W:';
s2='Shannon 编码平均码字长度L:';
s3='Shannon 编码的编码效率q:';
disp(s0);
disp(s1),disp(B),disp(s);
disp(s2),disp(L);
disp(s3),disp(q);
费诺编码的MATLAB 源程序
function[W,L,q]=fano(P)
if(length(find(P
error('Not a prob.vector,negative component');
end
if(abs(sum(P)-1)>10e-10)
error('Not a prob.vector,component do not add up to 1');
end
n=length(P);
x=1:n;
[P,x]=array(P,x);
for i=1:n
current_index=i;
j=1;
current_P=P;
while 1
[next_P,code_num,next_index]=compare(current_P,current_index);
current_index=next_index;
current_P=next_P;
W(i,j)=code_num;
j=j+1;
if(length(current_P)==1)
break;
end
end
l(i)=length(find(abs(W(i,:))~=0));
end
L=sum(P.*l);
H=entropy(P,2);
q=H/L;
for i=1:n
B{i}=i;
end
[n,m]=size(W);
TEMP=32*ones(n,5);
W=[W,TEMP];
W=W';
[n,m]=size(W);
W=reshape(W,1,n*m);
W=sprintf('%s',W);
s0='很好!输入正确,编码结果如下:';
s1='Fano 编码所得码字 W:';
s2='Fano 编码平均码字长度 L:';
s3='Fano 编码的编码效率 q:';
disp(s0);
disp(s1),disp(B),disp(W);
disp(s2),disp(L);
disp(s3),disp(q);
霍夫曼编码的MATLAB 源程序
function [W,L,q]=huffman(P)
if(length(find(P
error('Not a prob.vector,negative component');
end
if(abs(sum(P)-1)>10e-10)
error('Not a prob.vector,component do not add up to 1');
end
n=length(P);
p=P;
mark=zeros(n-1,n);
for i=1:n-1
[p,num]=sort(p);
mark(i,:)=[num(1:n-i+1),zeros(1,i-1)];
p=[p(1)+p(2),p(3:n),1];
end
for i=1:n-1
table(i,:)=blanks(n*n);
end
table(n-1,n)='1';
table(n-1,2*n)='0';
for i=2:n-1
table(n-i,1:n-1)=table(n-i+1,n*(find(mark(n-i+1,:)==1))-(n-2):n*(find(mark(n-i+1,:)==1)));
table(n-i,n)='1';
table(n-i,n+1:2*n-1)=table(n-i,1:n-1);
table(n-i,2*n)='0';
for j=1:i-1
table(n-i,(j+1)*n+1:(j+2)*n)=table(n-i+1,n*(find(mark(n-i+1,:)==j+1)-1)+1:n*find(mark(n-i+1,:)==j+1));
end
end
for i=1:n
W(i,1:n)=table(1,n*(find(mark(1,:)==i)-1)+1:find(mark(1,:)==i)*n);
l(i)=length(find(abs(W(i,:))~=32));
end
L=sum(P.*l);
H=entropy(P,2);
q=H/L;
for i=1:n
B{i}=i;
end;
[m,n]=size(W);
W=reshape(W',1,m*n);
s0='很好!输入正确,编码结果如下:';
s1='Huffman 编码所得码字 W:';
s2='Huffman 编码的平均码字长度L:';
s3='Huffman 编码的编码效率q:';
disp(s0);
disp(s1),disp(B),disp(W);
disp(s2),disp(L);
disp(s3),disp(q);