%%HUFFmann CODINg % %
%%close all
clear all
clc
%get names and prob in vectors
names=['a','b','c','d','e','f','g','h','i'];
prb=[0.64 0.016 0.144 0.016 0.0004 0.0036 0.1440 0.0036 0.0324];%sum(prb)==1
N=length(prb);%length prob
%make struct as follows
for i=1:N
p(i).name=names(i);%name
p(i).prob=prb(i);%prob
p(i).value=prb(i);%calc part
p(i).link=[];% link part
p(i).huff=[];% huff code
end
s=[p.value];
[~,m]=sort(s,'descend');
p=p(m);
for n=N:-1:2
%built in sort wont work..so this block
for z=n:-1:2
if([p(z).value]-[p(z-1).value]>10^-7)%prcision problem
temp0=p(z);
p(z)=p(z-1);
p(z-1)=temp0;
else break;
end
end
%add last two values
p(n-1).value = [p(n-1).value + p(n).value];
%uper last one gets 0 and lower gets 1 as in huff algrthm
p(n-1).huff=[0 p(n-1).huff];
p(n).huff=[1 p(n).huff];
%%update last-1 relatd links to 1 & last related links to 0
for i=[0 1]
L=length(p(n-i).link);%calculate lentgth of last-1 &last associated links
for j=1:L %update related members of links
temp=p(n-i).link(j);
[~,k]=find([p.name]==temp);
p(k).huff = [i==0 p(k).huff];
end
end
% now update,last link with last-1 link
p(n-1).link=[[p(n).name],p(n-1).link];];% put in bracket.. []
p(n-1).link=[p(n).link, p(n-1).link];
end
% display huff code
[~,m]=sort([p.name]);
p=p(m);
display('name prob huffcode')
for i=1:N
fprintf('|%2s -> %0.5f -> %|25s\n',[p(i).name],[p(i).prob],num2str([p(i).huff]))
end
%end
%RESULT
name prob huffcode
| a -> 0.64000 -> 0|
| b -> 0.01600 -> 1 0 1 0 1|
| c -> 0.14400 -> 1 1|
| d -> 0.01600 -> 1 0 1 0 0 0 |
| e -> 0.00040 -> 1 0 1 0 0 1 0 1|
| f -> 0.00360 -> 1 0 1 0 0 1 1|
| g -> 0.14400 -> 1 0 0 |
| h -> 0.00360 -> 1 0 1 0 0 1 0 0 |
| i -> 0.03240 -> 1 0 1 1 |