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

5 Ansichten (letzte 30 Tage)
Thanishka
Thanishka am 10 Aug. 2024
Bearbeitet: Jacob Mathew am 12 Aug. 2024
To compress the text file
  2 Kommentare
dpb
dpb am 10 Aug. 2024
huffmanenco is in Communications TB; there are some submissions on File Exchange although it appears all have more or fewer issues from discussions...
Walter Roberson
Walter Roberson am 10 Aug. 2024
There have been several postings giving huffman encoding code.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Jacob Mathew
Jacob Mathew am 12 Aug. 2024
Bearbeitet: Jacob Mathew am 12 Aug. 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);

Kategorien

Mehr zu Large Files and Big Data finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by