huffman.m

来自「jpeg在matlab下的仿真实现」· M 代码 · 共 37 行

M
37
字号
function CODE = huffman(p)
error(nargchk(1, 1,nargin));
if (ndims(p) ~=2) | (min(size(p)) > 1) | ~isreal(p) | ~isnumeric(p)
    error('P must be a real numeric vector.');
end

global CODE
CODE = cell(length(p), 1);
if length(p) > 1
    p = p / sum(p);
    s = reduce(p);
    makecode(s, []);
else
    CODE = {'1'};
end
function s = reduce(p);
for i = 1:length(p)
    s{i} = i;
end
while size(s) > 2
    [p, i] = sort(p);
    p(2) = p(1) + p(2);
    p(1) = [];
    s = s(i);
    s{2} {s{1}, s{2}};
 s(1) = [];
end
%-------------------------------------------------------%
function makecode(sc, codeword)
global CODE
if isa(sc, 'cell')
    makecode(sc{1}, [codeword 0]);
    makecode(sc{2}, [codeword 1]);
else
    CODE{sc} = char('0', + codeword);
end    
    

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?