close all;clear all;clc;
% 香农编码matlab实现
p = [0.5 0.19 0.19 0.07 0.05] %输入概率
n = length(p);
y = fliplr(sort(p));
D = zeros(n,4);
D(:,1) = y';
for i = 2:n
D(1,2) = 0;
D(i,2) = D(i-1,1)+D(i-1,2);
end
for i = 1:n
D(i,3) = -log2(D(i,1));
D(i,4) = ceil(D(i,3));
end
D
A = D(:,2)';
B = D(:,4)';
for j=1:n
C=binary1(A(j),B(j))
end
function [C] = binary1(A,B)
C=zeros(1,B);
temp = A;
for i=1:B
temp = temp*2;
if temp >= 1
temp = temp - 1;
C(1,i) = 1;
else
C(1,i) = 0;
end
end
end
输出结果:
p =
0.5000 0.1900 0.1900 0.0700 0.0500
D =
0.5000 0 1.0000 1.0000
0.1900 0.5000 2.3959 3.0000
0.1900 0.6900 2.3959 3.0000
0.0700 0.8800 3.8365 4.0000
0.0500 0.9500 4.3219 5.0000
C =
0
C =
1 0 0
C =
1 0 1
C =
1 1 1 0
C =
1 1 1 1 0
D中第一列表示输入概率,第二列表示累加概率,第四列表示对应输入概率的编码长度
C中按顺序对应D中相应输入概率的编码结果