Matlab Shannon编码实验
一、實驗目的:
(1)了解信源變長碼的編碼方法;
(2)掌握香農編碼方法;
(3)掌握MATLAB的編程。
?????????????????????????????????????????????????????????
二、實驗儀器:
Matlab2015a
三、實驗原理:???????????????????????????????????????????????????????????
1.將信源符號按概率從大到小順序排列,
?
2.按下式計算第i個符號對應的碼字的碼長
?
3.計算第i個符號的累加概率
4.將累加概率Pi變換成二進制小數,取小數點后li位數作為第i個符號的碼字。
四、實驗步驟:???????????????????????????????????????????????????????????????????????????????????????????????????????????????
1.先利用Matlab編寫函數;
2.再根據函數將實驗要求生成實驗結果;
3.根據實驗內容填寫實驗報告;??????????????????????????????????????????????????????????
五、實驗內容及數據整理: ?
用Matlab軟件編程實現Shannon編碼
???????????????????????????????????????????????????????????????????????????????????????????????????????
?六、實驗結果及討論??????????????????????????????????????????????????????????
?clc;clear;close all
%% 數據輸入
i = 1;
strTemp = ['請輸入第',num2str(i),'個概率(0退出):'];
p = [];
p(i) ?= input(strTemp);
while(p(end))
????i = i+1;
????strTemp = ['請輸入第',num2str(i),'個概率(0退出):'];
????temp = input(strTemp);
????p = [p temp];
end
eps = 1e-5;
if(sum(p)>1.0+eps || sum(p)<1.0-eps)
????error('概率和不等于1');
end
%% 初始化
n = length(p)-1; %由于最后一個數字為0
F = zeros(1,n);
logp = zeros(1,n);
L = zeros(1,n);
for?i = 2:n
????F(i) = F(i-1)+p(i-1);
????logp(i-1) = -log2(p(i-1));
????L(i-1) = ceil(logp(i-1));
end
logp(n) = -log2(p(n));
L(n) = ceil(logp(n));
?%% 編碼過程
for?i = 1:n
????temp1 = L(i);
????temp2 = [];
????temp3 = F(i);
????while(temp1)
????????temp4 = fix(2*temp3);
????????temp3 = 2*temp3 - temp4;
????????temp2 = [temp2 ?num2str(temp4)];
????????temp1 = temp1 - 1;
????end
????fprintf('第%d個的香農編碼為:%s\n',i,temp2);
end
?第二種方法:
clc;clear;close all m=input('Enter the no.of message ensembles:'); %輸入概率 z=[]; h=0; l=0; display('Enter the probabilities in descending order:') %按降序輸入概率 for i=1:mfprintf('Ensemble%d\n',i); %總體均值p(i)=input(''); end%Finding each alpha values 找到每個值 a(1)=0; for j=2:m;a(j)=a(j-1)+p(j-1); end fprintf('\n Alpha Matrix'); display(a);%Finding each code length for i=1:mn(i)=ceil(-1*(log2(p(i)))); end fprintf('\n Code length matrix'); display(n);%Computing each code for i=1:mint=a(i);for j=1:n(i)frac=int*2c=floor(frac);frac=frac-c;z=[z c];int=frac;endfprintf('Codeword %d',i);display(z);z=[]; end%Computing Avg.Code Length & Entropy fprintf('Avg.Code Length'); for i=1:mx=p(i)*n(i);l=l+x;x=p(i)*log2(1/p(i));h=h+x; end display(l); fprintf('Entropy'); display(h);%Computing Efficiency fprintf('Efficiency'); display(100*h/l); fprintf('Redundancy'); display(100-(100*h/l));?
總結
以上是生活随笔為你收集整理的Matlab Shannon编码实验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Matlab Shannon编码
- 下一篇: shannon