簡單的matlab實現哈夫曼(Huffman)編碼

2021-10-07 02:48:42 字數 1906 閱讀 5591

影象處理結課專案中有乙個haffman編碼的實現,打算用matlab來做。準備考研,小半年沒寫過**了,寫出來後居然一遍過,有點小確幸,記錄一下這個過程的思路。

先看了一下哈夫曼樹的構造形式,觀察發現從自頂而下的角度,哈夫曼編碼相當於對權重做了多次判決,在每次判決中,我們關心次小的那權重,因為需要對其哈夫曼編碼前補1,且對於最小的那權重,需要在其編碼前補0,而且如果我們在每次判決之後,都將最小的那組權重的值,加上次小的那個權重的值,這個過程就是乙個迴圈的過程,當然也可以說是遞迴的過程。那麼大體的思路就有了。

**如下:

其中encode.txt是待編碼的檔案

%匯入txt並進行排序,準備工作

filename = "encode.txt";

fileid = fopen(filename);

c = textscan(fileid,'%c');

fclose(fileid);

class = c;

table = tabulate(class);

charname = cell2mat(table(:,1));

freq = cell2mat(table(:,2));

[freq,weight] = sort(freq,'descend'); %降序

charname = charname(weight);

n = length(charname);

freq_changable = freq;

%哈夫曼編碼

huffman_encode = strings(1,n);%empty string martrix

for i=1:(n-1)

[freq_changable,weight] = sort(freq_changable,'descend'); %降序

charname = charname(weight);

freq = freq(weight);

huffman_encode = huffman_encode(weight);

%降序if(freq_changable(n)==freq_changable(n-1))

for j=n-i+1:n

if(freq_changable(j)==freq_changable(n))

huffman_encode(j) = insertbefore(huffman_encode(j),1,'0');%補零

freq_changable(j) = freq_changable(j)+freq_changable(n-i);

endend

huffman_encode(n-i) = insertbefore(huffman_encode(n-i),1,'1');

freq_changable(n-i) = freq_changable(n-i+1);

else

for j=n-i:n-1

if(freq_changable(j)==freq_changable(n-1))

huffman_encode(j) = insertbefore(huffman_encode(j),1,'1');%補一

freq_changable(j) = freq_changable(j)+freq_changable(n);

endend

huffman_encode(n) = insertbefore(huffman_encode(n),1,'0');

freq_changable(n) = freq_changable(n-1);

endend

%輸出for i=1:n

fprintf('字元%c的編碼是%s\n',charname(i),huffman_encode(i));

end

Matlab程式設計 哈夫曼編碼的Matlab實現

在前年暑假的時候,用c實現了哈夫曼編譯碼的功能,見文章 哈夫曼樹及編譯碼 不過在通訊 中,經常要使用到matlab程式設計,所以為了方便起見,這裡用matlab實現的哈夫曼編碼的功能。至於哈夫曼編譯碼的基本原理,我們可以參考之前的文章 哈夫曼樹及編譯碼 裡面有詳細的說明及 過程。下面直接給出具體的m...

C 哈夫曼樹及哈夫曼編碼的實現

huffmancode.h ifndef huffmancode h define huffmancode h include typedef struct htnode,huffmantree typedef char huffmancode void huffmancoding huffmant...

哈夫曼樹與哈夫曼編碼的實現 python

建立節點類,用於每個節點的生成 class hfmnode def init self self.name none self.weight none self.leftchild none self.rightchild none self.parent none 構建哈夫曼樹 def creat...