编写一份matlab代码完成文件里的要求
时间: 2024-10-19 14:12:10 浏览: 36
MatLab代码大全.rar_matlab 代码查询_matlab代码大全
5星 · 资源好评率100%
为了完成《Assignment1.pdf》中的任务,以下是一个完整的MATLAB脚本示例,包括了Huffman编码和Shannon-Fano编码的实现、熵计算、字符串编码、效率分析以及结果展示。请注意,这个脚本假设所有函数都定义在一个单独的`.mlx`文件中,并且符合提交指南的要求。
### `FirstNameLastName.mlx`
```matlab
%% Beijing Dublin International College EEEN3017J - Information Theory & Coding
% Assignment 1: Implement and Compare Huffman Coding and Shannon-Fano Coding
%
% Author: FirstName LastName
% Date: 2023-10-10
%% Input Setup
Symbols = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
Probabilities = [0.25, 0.2, 0.15, 0.12, 0.1, 0.08, 0.06, 0.04];
SampleString = 'AABCCDEFGH';
%% Entropy Calculation
function H = calculateEntropy(probabilities)
H = -sum(probabilities .* log2(probabilities));
end
Entropy = calculateEntropy(Probabilities);
fprintf('Entropy (H): %.4f bits/symbol\n', Entropy);
%% Huffman Coding Implementation
function [huffmanCodes, huffmanTree] = huffmanCoding(symbols, probabilities)
% Create nodes
nodes = arrayfun(@(s, p) struct('symbol', s, 'probability', p), symbols, probabilities, 'UniformOutput', false);
% Build the Huffman tree
while length(nodes) > 1
% Sort nodes by probability
nodes = sortrows([nodes{:}], 'probability');
% Combine the two smallest nodes
leftNode = nodes{1};
rightNode = nodes{2};
combinedNode = struct('symbol', [], 'probability', leftNode.probability + rightNode.probability, ...
'left', leftNode, 'right', rightNode);
% Remove the two smallest nodes and add the combined node
nodes(1:2) = [];
nodes{end+1} = combinedNode;
end
huffmanTree = nodes{1};
% Generate Huffman codes
huffmanCodes = cell(size(symbols));
generateHuffmanCodes(huffmanTree, '', huffmanCodes);
end
function generateHuffmanCodes(node, code, codes)
if ~isfield(node, 'left') && ~isfield(node, 'right')
index = find(strcmp({codes.symbol}, node.symbol));
codes{index}.code = code;
else
if isfield(node, 'left')
generateHuffmanCodes(node.left, [code '0'], codes);
end
if isfield(node, 'right')
generateHuffmanCodes(node.right, [code '1'], codes);
end
end
end
[HuffmanCodes, HuffmanTree] = huffmanCoding(Symbols, Probabilities);
disp('Huffman Codes:');
for i = 1:length(Symbols)
fprintf('%s: %s\n', Symbols{i}, HuffmanCodes(i).code);
end
%% Shannon-Fano Coding Implementation
function shannonFanoCodes = shannonFanoCoding(symbols, probabilities)
% Recursive function to split symbols
function codes = splitSymbols(symbols, probabilities, codePrefix)
n = length(symbols);
if n == 1
codes = containers.Map({'Code'}, {codePrefix});
return;
end
% Find the best split point
cumulativeSum = cumsum(probabilities);
minDiff = inf;
splitPoint = 1;
for k = 1:(n-1)
diff = abs(cumulativeSum(k) - (cumulativeSum(end) - cumulativeSum(k)));
if diff < minDiff
minDiff = diff;
splitPoint = k;
end
end
% Split and assign codes
codes = containers.Map();
leftSymbols = symbols(1:splitPoint);
leftProbabilities = probabilities(1:splitPoint);
rightSymbols = symbols(splitPoint+1:end);
rightProbabilities = probabilities(splitPoint+1:end);
leftCodes = splitSymbols(leftSymbols, leftProbabilities, [codePrefix '0']);
rightCodes = splitSymbols(rightSymbols, rightProbabilities, [codePrefix '1']);
codes = [codes, leftCodes, rightCodes];
end
% Initial call to recursive function
shannonFanoCodes = splitSymbols(symbols, probabilities, '');
end
ShannonFanoCodes = shannonFanoCoding(Symbols, Probabilities);
disp('Shannon-Fano Codes:');
for i = 1:length(Symbols)
fprintf('%s: %s\n', Symbols{i}, ShannonFanoCodes(Symbols{i}));
end
%% String Encoding
function encodedString = encodeString(inputString, codes)
encodedString = '';
for i = 1:length(inputString)
symbol = inputString(i);
encodedString = [encodedString codes(symbol)];
end
end
HuffmanEncodedString = encodeString(SampleString, containers.Map(HuffmanCodes));
ShannonFanoEncodedString = encodeString(SampleString, ShannonFanoCodes);
disp('Encoded Strings:');
fprintf('Huffman: %s\n', HuffmanEncodedString);
fprintf('Shannon-Fano: %s\n', ShannonFanoEncodedString);
%% Efficiency Analysis
function [averageCodeLength, compressionRatio, redundancy, codingEfficiency] = calculateEfficiency(codes, probabilities, entropy, originalSize)
codeLengths = cellfun(@length, values(codes));
averageCodeLength = sum(codeLengths .* probabilities);
compressedSize = averageCodeLength * originalSize;
compressionRatio = originalSize / compressedSize;
redundancy = averageCodeLength - entropy;
codingEfficiency = (entropy / averageCodeLength) * 100;
end
originalSize = length(SampleString);
[avgLenHuffman, compRatioHuffman, redunHuffman, effHuffman] = calculateEfficiency(containers.Map(HuffmanCodes), Probabilities, Entropy, originalSize);
[avgLenShannonFano, compRatioShannonFano, redunShannonFano, effShannonFano] = calculateEfficiency(ShannonFanoCodes, Probabilities, Entropy, originalSize);
disp('Efficiency Metrics:');
fprintf('Huffman:\nAverage Code Length: %.4f\nCompression Ratio: %.4f\nRedundancy: %.4f\nCoding Efficiency: %.2f%%\n', avgLenHuffman, compRatioHuffman, redunHuffman, effHuffman);
fprintf('Shannon-Fano:\nAverage Code Length: %.4f\nCompression Ratio: %.4f\nRedundancy: %.4f\nCoding Efficiency: %.2f%%\n', avgLenShannonFano, compRatioShannonFano, redunShannonFano, effShannonFano);
%% Mathematical Proof & Justification
% Huffman coding is generally more efficient because it always generates the optimal prefix-free code,
% minimizing the average code length. Shannon-Fano coding, while simpler, may not always produce the
% most efficient code due to its top-down approach.
%% Visualizations
metrics = {'Entropy', 'Average Code Length', 'Compression Ratio', 'Redundancy', 'Coding Efficiency'};
valuesHuffman = [Entropy, avgLenHuffman, compRatioHuffman, redunHuffman, effHuffman];
valuesShannonFano = [Entropy, avgLenShannonFano, compRatioShannonFano, redunShannonFano, effShannonFano];
figure;
bar(metrics, [valuesHuffman; valuesShannonFano]');
set(gca, 'XTickLabel', metrics, 'XTickLabelRotation', 45);
legend('Huffman', 'Shannon-Fano');
ylabel('Value');
title('Comparison of Huffman and Shannon-Fano Coding');
%% Summary
fprintf('Summary:\n');
if effHuffman > effShannonFano
fprintf('Huffman coding is more optimal.\n');
else
fprintf('Shannon-Fano coding is more optimal.\n');
end
```
### 提交说明
1. 将上述代码保存为 `FirstNameLastName.mlx` 文件。
2. 运行该脚本以生成所需的结果。
3. 将生成的结果和分析整理成一个详细的PDF报告,按照提交指南的要求进行提交。
希望这段代码能帮助你顺利完成作业!如果有任何问题或需要进一步的帮助,请随时告诉我。
阅读全文