最近在学习中,需要用到用MATLAB编写方程来实现一维多元离散信源熵的计算,下面是相应的程序和改进程序:
format short
p = input('p = ') %input any discrete one-dimensional probability distribution
if sum(p) ~= 1,
error('p is error,sum is not 1') %check whether the sum of probability is 1
end
zerop = find(p == 0);
if ~isempty(zerop), %remove the symbol of zero probability
p(zerop) = [];
end
H = -sum(p.*log2(p)); %entropy formula
fprintf('entropy is:%d(bit/symbol)',H)
因为matlab本身存在精度问题,我对上述程序进行改进
改进程序
format short
p = input('intput any one-dimensional discrete probability distribution p = ')
if abs(sum(p) - 1) > 1e-8
error('p is eror,sum is not 1')
end
zerop = find(p === 0);
if ~isempty(zerop),
p(zerop) = [];
end
H = -sum(p.*log2(p));
disp('entropy