clc,clear all;
symbol=['abc'];
pr=[0.3 0.4 0.3]; %各字符出现的概率
temp=[0.0 0.3 0.7 1.0];
orignal=temp;
in=input('input a string of abc:');
n=length(in);
%编码
for i=1:n
width=temp(4)-temp(1);
w=temp(1);
switch in(i)
case 'a'
m=1;
case 'b'
m=2;
case 'c'
m=3;
otherwise
error('do not input other character');
end
temp(1)=w+orignal(m)*width;
temp(4)=w+orignal(m+1)*width;
left=temp(1);
right=temp(4);
fprintf('left=%.6f',left);
fprintf(' ');
fprintf('right=%.6f\n',right);
end
encode=(temp(1)+temp(4))/2
%解码
decode=['0'];
for i=1:n
fprintf('tmp=%.6f\n',encode);
if(encode>=orignal(1)& encode<orignal(2))
decode(i)='a';
t=1;
elseif(encode>=orignal(2)& encode<orignal(3))
decode(i)='b';
t=2;
else
decode(i)='c';
t=3;
end
encode=(encode-orignal(t));
encode=encode/pr(t);
end
decode
%算术编码的编码对象是一则消息或一个字符序列,其编码思路是将消息或字符序列表示成0和1之间的一个间隔上的一个浮点小数。
%在进行算术编码之前,需要对字符序列中每个字符的出现概率进行统计,根据各字符出现概率的大小,将每个字符映射到[0 ,1]区间上的某个子区间中。然后,在利用递归算法,将整个字符序列映射到[0,1 ]区间上的某个间隔中。在进行编码时,只需从该间隔中任选一个小数,将其转化为二进制数。
% 符号序列越长,编码表示他的间隔就越小,表示这个间隔所需的二进制位数就越多,编码输出的码字就越长。
%
% 算术编码规则:
% 在进行编码过程中,随着信息的不断出现,子区间按下列规律减小。
% ①新子区间左端=前子区间左端+当前子区间左端×前子区间长度。
% ②新子区间长度=前子区间长度×当前子区间长度。