Huff Man Coding Matlab
Huff Man Coding Matlab
end end for m=1:length(sym) for n=m+1:length(sym) if(sym(m)==sym(n)) sym(m)=[' ']; sym=sym; end end end if(no_space==0) for m=1:length(sym) if(sym(m)~=' ') text_mod=[text_mod,sym(m)]; end end end if(no_space==1) for m=1:length(sym) if(sym(m)~=' ') text_mod=[text_mod,sym(m)]; end end end if (no_space==0) text_mod=[text_mod,' ']; sym=text_mod; end if (no_space==1) sym=text_mod; end
%format ['a','b','c','d','e','f'];
for m=1:length(sym) ascii_value(m)=double(sym(m)); end i=1; for m=1:length(ascii_value) for n=1:length(ascii_value) if(ascii_value(m)>ascii_value(n)) a=ascii_value(n); a1=sym(n); ascii_value(n)=ascii_value(m);sym(n)=sym(m); ascii_value(m)=a; sym(m)=a1; end end end tempfinal=[0]; sumarray=[]; w=length(ascii_value);
lengthp=[w]; b(i,:)=ascii_value; huff_code=[]; huff_code_final=[]; while(length(ascii_value)>2) tempsum=ascii_value(length(ascii_value))+ascii_value(length(ascii_value)-1); sumarray=[sumarray,tempsum]; ascii_value=[ascii_value(1:length(ascii_value)-2),tempsum]; ascii_value=sort(ascii_value,'descend'); i=i+1; b(i,:)=[ascii_value,zeros(1,w-length(ascii_value))]; %huffman tree formation b has i number of rows and no limit on columns w1=0; lengthp=[lengthp,length(ascii_value)]; for temp=1:length(ascii_value) if ascii_value(temp)==tempsum; w1=temp; end end tempfinal=[w1,tempfinal]; % Find the place where tempsum has been inserted end sizeb(1:2)=size(b); %sizeb has number of rows as first element and number of columns as second element tempdisplay=0; temp2=[]; for i= 1:sizeb(2) temp2=[temp2,b(1,i)]; end sumarray=[0,sumarray]; e=1; for ifinal= 1:sizeb(2) code=['']; for j=1:sizeb(1) tempdisplay=0; for i1=1:sizeb(2) if( b(j,i1)==temp2(e)) tempdisplay=b(j,i1); end if(tempdisplay==0 && b(j,i1)==sumarray(j)) tempdisplay=b(j,i1); end end if tempdisplay==b(j,lengthp(j)) %assign 0 & 1 code=[code,'1']; elseif tempdisplay==b(j,lengthp(j)-1) code=[code,'0']; else code=[code,'']; end temp2(e)=tempdisplay; end huff_code=[huff_code,' ',code]; e=e+1; end for m=1:length(text_input) for i=1:length(sym) k=0;
if(text_input(m)==sym(i)) for(j=1:length(huff_code)) if(huff_code(j)==' ') k=k+1; end if(k==i) huff_code_final=[huff_code_final,huff_code(j)]; end end end end end display(' '); display('Given text is :'); display(text_input); display('The required huffman code is :'); display(huff_code_final);