How can I compress text file by Huffman encoding method by using matlab

5 visualizzazioni (ultimi 30 giorni)
To compress the text file
  2 Commenti
dpb
dpb il 10 Ago 2024
huffmanenco is in Communications TB; there are some submissions on File Exchange although it appears all have more or fewer issues from discussions...

Accedi per commentare.

Risposte (1)

Jacob Mathew
Jacob Mathew il 12 Ago 2024
Modificato: Jacob Mathew il 12 Ago 2024
Hey Thanishka,
I understand that you want to encode text file using hoffman encoding. You can use the below link to get started on huffman encoding. The documentation also has example code to help you understand the usage of the "huffmanenco" , "huggmandeco" and "huffmandict" function:
To get up and running, you can reference the following code that shows how to read a text file, encode it using Huffman encoding and then decode it.
Note that string values cannot directly be encoded ad hence we are going to convert them to double first:
function huffman_encoding(inputFile, outputFile)
% Read the input text file
fileID = fopen(inputFile, 'r');
text = fscanf(fileID, '%c');
fclose(fileID);
% Calculate the frequency of each character
symbols = unique(text);
freq = histc(text, symbols);
% Map characters to numerical values
numSymbols = double(symbols);
% Create Huffman dictionary
[dict, avglen] = huffmandict(numSymbols, freq / sum(freq));
% Encode the text
numText = double(text);
encodedText = huffmanenco(numText, dict);
% Save the encoded text and dictionary to a .mat file
save(outputFile, 'encodedText', 'dict', 'symbols');
disp(['Text has been encoded and saved to ', outputFile]);
end
% Function to decode the Huffman encoded text
function decodedText = huffman_decoding(encodedFile)
% Load the encoded text and dictionary from the .mat file
load(encodedFile, 'encodedText', 'dict', 'symbols');
% Decode the text
numDecodedText = huffmandeco(encodedText, dict);
% Convert numerical values back to characters
decodedText = char(numDecodedText);
end
% Encode the text
huffman_encoding('input.txt', 'encoded.mat');
% Decode the text
decodedText = huffman_decoding('encoded.mat');
disp(decodedText);

Categorie

Scopri di più su Large Files and Big Data in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by