# huffman code impelementation manual not use the built in function

1 view (last 30 days)
Shehab Tarek on 23 May 2020
Commented: Walter Roberson on 25 May 2020
hi guys any one can help me in huffman code (data compression) to be more efficiency
this code is already working but i need it to be general and more efficiency i already use the built in code to insure
clc;
clear all;
close all;
l=6;
o=5;
matrix=[0.3 0.3 0.3 0.43 0.57 1;
0.25 0.25 0.27 0.3 0.43 0;
0.15 0.18 0.25 0.27 0 0
0.12 0.15 0.18 0 0 0;
0.1 0.12 0 0 0 0;
0.08 0 0 0 0 0;];
code=cell(6,6);
index=[3,2,1,1];
code{1,6}=1; %%%
code{1,5}=0; %%%
code{2,5}=1; %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
number1=2;
number2=3;
num1=2;
number=5; % number of colum
prob=[0.3 0.25 0.15 0.12 0.1 0.08 ];
[dict,avglen] = huffmandict(1:6,prob);
rr=[];
%%%% clear the zero in matrix %%%
for i=5:-1:2
a=intersect(matrix(:,i),matrix(:,i-1));%% intersect the the element
code{num1,number-1}=[0,code{index(i-1),number}];
code{num1+1,number-1}=[1,code{index(i-1),number}];
number=number-1;
num1=num1+1;
[ll,~]=size(a); %% size of output matrix
for ii=1:ll
a(a==0)=[]; %% clear zero in array
end
[l_new,~]=size(a); %% the new size of matrix after the clear operation
for iu=1:l_new
y=find(a(iu)==matrix(:,i)); %% find the element
rr=[rr y];
rr=sort(rr,'descend');
rr=flip(rr);
end
b=cell(1,l_new); %% create new cell have the index of element
%%%%%this is cmulative function according the index value%%%%
for iy=1:l_new
b{1,iy}=code{rr(iy),i};
for iv=1:l_new
code{iv,i-1}=b{1,iv};
end
end
rr=[];
b={};
end
%%%%%%%%%%%%%%%%%%%final answer to calculate the average length%%%%%%%%%%%
code=code(:,1);
length=[];
matrix=[];
for i=1:l
code{i}=flip(code{i});
[~,c]=size(code{i});
length=[length c];
s=code{i};
matrix=[matrix s];
end
avl=0;
for i=1:l
average_length=prob(i)*length(i);
avl=avl+average_length;
end
Walter Roberson on 25 May 2020
no, after one iteration all of the remaining zeros are gone and you can stop.