make huffman coding algorithm in matlab

To implement Huffman coding algorithm in MATLAB, you can follow these steps:

Step 1: Calculate the frequency of each symbol in the input data

main.m
function freq = calculateFrequency(data)
    symbols = unique(data);
    freq = zeros(size(symbols));
    for i = 1:length(symbols)
        freq(i) = sum(data == symbols(i));
    end
end
187 chars
8 lines

Step 2: Build the Huffman tree from the frequency table

main.m
function tree = buildHuffmanTree(freq)
    symbols = unique(1:length(freq));
    [~, symbols_sorted] = sort(freq, 'descend');
    
    while numel(symbols_sorted) > 1
        s1 = symbols_sorted(end);
        s2 = symbols_sorted(end-1);
        symbols_sorted = symbols_sorted(1:end-2);
        weight = freq(s1) + freq(s2);
        freq = [freq(1:end-2); weight];
        symbols_sorted = [symbols_sorted; max(symbols)+1];
        symbols = [symbols; {[symbols{s1}, symbols{s2}]}];
    end
    
    tree = symbols{1};
end
523 chars
17 lines

Step 3: Generate the Huffman codes for each symbol

main.m
function codes = generateHuffmanCodes(tree)
    codes = cell(size(tree));
    for i = 1:length(tree)
        code = '';
        node = tree{i};
        while ~isempty(node)
            if node(1) == 0
                code = [code, '0'];
                node = node(2:end);
            else
                code = [code, '1'];
                node = node(2:end);
            end
        end
        codes{i} = code;
    end
end
427 chars
18 lines

Step 4: Compress the input data using the Huffman codes

main.m
function compressedData = compressData(data, codes)
    compressedData = '';
    for i = 1:length(data)
        symbol = data(i);
        code = codes{symbol};
        compressedData = [compressedData, code];
    end
end
221 chars
9 lines

Step 5: Run the Huffman coding algorithm on your data

main.m
data = [1, 5, 3, 2, 5, 1, 4, 2, 3, 3];

freq = calculateFrequency(data);
tree = buildHuffmanTree(freq);
codes = generateHuffmanCodes(tree);
compressedData = compressData(data, codes);
184 chars
7 lines

Make sure to replace data with your own input data.

Please note that this is a basic implementation of the Huffman coding algorithm in MATLAB. Depending on your specific requirements, you may need to modify and optimize it further.

related categories

gistlibby LogSnag