Code covered by the BSD License  

Highlights from
Shannon-fano encoder

Shannon-fano encoder

by

 

13 May 2013 (Updated )

a shannonfano encoder with a row matrix input of occurrences/probab and outputs codewords&avelength

sfencoder.m
aa=fopen('C:\Users\mariska\Desktop\FF7.txt');
bb=fread(aa);
cc=unique(bb); %find used characters
taas=length(bb);
for n=1:length(cc)
    d(n,1)=length(find(bb==cc(n))); %count the occurence of a character
    
end
ss=transpose(d)./taas;
ss=sort(ss,'descend');
siling=ceil(log2(1/ss(1)));
sf=0;
fano=0;
n=1;Hs=0;
for iii=1:length(ss)
   Hs=Hs+ ss(iii)*log2(1/ss(iii));
end
shano=ss(1);
for o=1:length(ss)-1
   fano=fano+ss(o);
   sf=[sf 0]+[zeros(1,o) fano]; 
   siling=[siling 0]+[zeros(1,o) ceil(log2(1/ss(o+1)))];
end

for r=1:length(sf)
    esf=sf(r);
    
    for p=1:siling(r)
    
        esf=mod(esf,1)*2;
        h(p)=esf-mod(esf,1);
        
    end
    hh(r)=h(1)*10^(siling(r)-1);
    for t=2:siling(r)
        hh(r)=hh(r)+h(t)*10^(siling(r)-t);    
    end
end
c={'0','1'};
for i=1:length(hh)
    u=1;
   for t=siling(i):-1:1
       f=floor(hh(i)/10^(t-1));
       hh(i)=mod(hh(i),10^(t-1));       
       if f==1
           if u==1
                d=c{2};
           else
                d=[d c{2}];
           end
       else
           if u==1
                d=c{1};
           else
                d=[d c{1}];
           end
       end
       codex{i,:}={d};
       u=u+1;
   end
end
tao=siling(1)*ss(1);
for u=1:length(ss)-1
   tao=tao+siling(u+1)*ss(u+1);
end
T=tao/n;
B=[flipud(rot90(ss)),flipud(rot90(siling)),flipud(rot90(sf))];
disp(['       s','        Li','        Pk'])
disp(B)
disp('Code')
disp(codex)
disp(['Hs = ',num2str(Hs)])
disp(['T = ',num2str(T),'bits/symbol'])
disp([num2str(Hs),' <= ',num2str(T),' <= ',num2str(Hs+1)])

Contact us