1 ## Copyright (C) 2006 Muthiah Annamalai <muthiah.annamalai@uta.edu>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} {} shannonfanodict (@var{symbols},@var{symbol_probabilites})
19 ## Returns the code dictionary for source using shanno fano algorithm.
20 ## Dictionary is built from @var{symbol_probabilities} using the shannon
21 ## fano scheme. Output is a dictionary cell-array, which
22 ## are codewords, and correspond to the order of input probability.
26 ## CW=shannonfanodict(1:4,[0.5 0.25 0.15 0.1]);
27 ## assert(redundancy(CW,[0.5 0.25 0.15 0.1]),0.25841,0.001)
28 ## shannonfanodict(1:5,[0.35 0.17 0.17 0.16 0.15])
29 ## shannonfanodict(1:8,[8 7 6 5 5 4 3 2]./40)
33 ## @seealso{shannonfanoenc, shannonfanodec}
35 function cw_list=shannonfanodict(symbol,P)
38 error('Usage: shannonfanodict(symbol,P); see help');
44 if(sum(P)-1.000 > 1e-7)
45 error('Sum of probabilities must be 1.000');
48 #FIXME: Is there any other way of doing the
49 #topological sort? Insertion sort is bad.
51 #Sort the probability list in
52 #descending/non-increasing order.
53 #Using plain vanilla insertion sort.
75 #Now for each symbol you need to
76 #create code as first [-log p(i)] bits of
77 #cumulative function sum(p(1:i))
79 #printf("Shannon Codes\n");
80 #data_table=zeros(1,DMAX);
85 digits=ceil(-log2(P(itr))); #somany digits needed.
87 digits=0; #dont assign digits for zero probability symbols.
90 Psum = sum([0 P](1:itr)); #Cumulative probability
104 #re-arrange the list accroding to input prob list.
106 for i=1:length(cw_list)
107 cw_list2{i}=cw_list{S(i)};
116 %! P = [0.5 0.25 0.15 0.1];
117 %! assert(shannonfanodict(1:4,P),{[0],[1 0],[1 1 0],[1 1 1 0]})