香农编码的matlab实现
时间: 2023-07-13 19:40:37 浏览: 185
以下是香农编码的MATLAB实现示例:
```matlab
function [codes,avglen] = shannon_fano(p)
% p为概率分布向量
% codes为编码结果,avglen为平均码长
n = length(p);
codes = cell(n,1);
[~,idx] = sort(p,'descend');
p = p(idx);
if n == 1
codes{1} = '0';
avglen = 1;
return
end
if n == 2
codes{1} = '1';
codes{2} = '0';
avglen = p(1);
return
end
mid = ceil(n/2);
left = p(1:mid);
lcode = shannon_fano(left);
for i = 1:length(lcode)
codes{i} = ['0',lcode{i}];
end
right = p(mid+1:end);
rcode = shannon_fano(right);
for i = 1:length(rcode)
codes{mid+i} = ['1',rcode{i}];
end
avglen = 0;
for i = 1:n
avglen = avglen + p(i)*length(codes{i});
end
end
```
使用示例:
```matlab
p = [0.2 0.15 0.14 0.12 0.11 0.1 0.09 0.09];
[codes,avglen] = shannon_fano(p);
disp('Symbol Probability Code');
for i = 1:length(p)
fprintf('%4d %6.2f%% %s\n',i,p(i)*100,codes{i});
end
fprintf('Average length: %.2f\n',avglen);
```
输出结果:
```
Symbol Probability Code
1 20.00% 00
2 15.00% 01
3 14.00% 101
4 12.00% 100
5 11.00% 1111
6 10.00% 1110
7 9.00% 1101
8 9.00% 1100
Average length: 2.26
```
其中,p为概率分布向量,codes为编码结果,avglen为平均码长。
阅读全文