问题
I need Matlab code that solves the example problems below. According to the probability values of the symbols I have given, the huffman code will find its equivalent, step by step. If you help me, i will be very happy. I've put examples of this below. All of them have obvious solutions.
For example:
Symbol Probability
a1 enter probability value input
a2 enter probability value input
a3 enter probability value input
a4 enter probability value input
a5 enter probability value input
a6 enter probability value input
. .
. .
an enter probability value input
Output:
a1 1
a2 011
a3 01101
a4 10000
a5 11001
a6 10010
. .
. .
. .
an .
L average= .............................
example 1
example 2
example 3
example 4
My tried code block:
function [huffcode,n]=huffmancode(p);
if min(p)<0
error('Negative element cannot be in a probability vector')
return
else if abs(sum(p)-1)>1.e-12
error('Sum of input probability is not 1')
return
end
[psort,pord]=sort(p);
n=lenght(p);
q=p;
for i=1:n-1
[q,1]=sort(q);
m(i,:)=[1(1:n-i+1),zeros(1,i-1)];
q=[q(1)+q(2),q(3:end),1];
end
Cword=blanks(n^2);
Cword(n)='0';
Cword(2+n)='1';
for i1=1:n-2
Ctemp=Cword;
idx0=find(m[n-i],:)==)*n;
Cword(1:n)=[(idx0-n+2:idx0) '0'];
Cword(n+1:2*n)=[Cword(1:n-1 '1'];
for i2=2:i1+1
idx2=find(m(n-i1,:)==i2);
Cword(i2*n+1:(i2+1)*n)=Ctemp(n*(idx2-1)+1:n*idx2);
end
end
for i=1:n
idx1=find(m(1,:)==i);
huffcode(i,1:n)=Cword(n*(idx1-1)+1:idx1*n);
end
.................................................................................................................................................................................................................................
p=[0.4 0.3 0.1 0.1 0.06 0.04];
[huffcode,n]=huffmancode(p);
entropy=sum(-log(p)*p')/log(2);
display(['symbol','-->',' codeword', Probability'])
for i=1:n
codeword_length(i)=n-length(find(abs(huffcode(i,:))==32));
display(['x',num2str(i),' -->',huffcode(i,:),' ',num2str(p(i))]);
end
codeword_Lenght
avg_length=codeword_Length*p';
display(['Entropy = ', num2str(entropy)])
display(['Average codeword length = ', num2str(avg_length)])
....................................................................................................................
for detailed explanation: https://www.programmersought.com/article/34164094982/
来源:https://stackoverflow.com/questions/65760255/huffman-and-average-length