根据文件中的要求与内容用2020b版本matlab编写脚本文件以及相关程序
时间: 2024-10-19 19:10:34 浏览: 33
为了完成《Assignment1.pdf》中描述的任务,你需要使用MATLAB 2020b编写一个脚本文件(`.mlx`),并实现以下功能:
### 1. 输入设置
定义一组8个符号及其对应的概率。
```matlab
% Define symbols and their probabilities
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];
```
### 2. 计算熵
计算给定源的熵,并解释其意义。
```matlab
function H = calculateEntropy(probabilities)
% Calculate the entropy
H = -sum(probabilities .* log2(probabilities));
end
% Call the function
H = calculateEntropy(Probabilities);
disp(['Entropy (H): ', num2str(H)]);
```
### 3. 实现霍夫曼编码和香农-范诺编码
#### 霍夫曼编码
创建自定义函数来生成霍夫曼树和霍夫曼码。
```matlab
function [codes, avgLength] = huffmanCoding(symbols, probabilities)
% Create a priority queue (min heap)
T = struct('symbol', {}, 'probability', [], 'left', [], 'right', []);
% Initialize the leaves
for i = 1:length(symbols)
node = struct('symbol', symbols{i}, 'probability', probabilities(i), 'left', [], 'right', []);
T = [T; node];
end
% Build the Huffman tree
while length(T) > 1
% Sort nodes by probability
T = sortrows(T, 'probability');
% Take the two nodes with the smallest probabilities
leftNode = T(1);
rightNode = T(2);
% Create a new internal node
newNode = struct('symbol', [], 'probability', leftNode.probability + rightNode.probability, 'left', leftNode, 'right', rightNode);
% Remove the two nodes with the smallest probabilities
T(1:2) = [];
% Add the new node to the tree
T = [T; newNode];
end
% Generate Huffman codes
codes = cell(length(symbols), 1);
generateCodes(T{1}, '', codes);
% Calculate the average code length
avgLength = sum(cellfun(@length, codes) .* probabilities);
end
function generateCodes(node, code, codes)
if ~isempty(node.symbol)
codes{strcmp(codes, '') + 1} = code;
else
generateCodes(node.left, [code '0'], codes);
generateCodes(node.right, [code '1'], codes);
end
end
```
#### 香农-范诺编码
创建自定义函数来生成香农-范诺码。
```matlab
function [codes, avgLength] = shannonFanoCoding(symbols, probabilities)
% Sort symbols by probability in descending order
[probabilities, idx] = sort(probabilities, 'descend');
symbols = symbols(idx);
% Split the list into two parts with approximately equal probability
splitIndex = find(cumsum(probabilities) >= 0.5, 1);
% Assign binary codes recursively
codes = cell(size(symbols));
assignCodes(symbols, probabilities, 1, splitIndex, '0', codes);
assignCodes(symbols, probabilities, splitIndex+1, length(symbols), '1', codes);
% Reorder codes to match original symbol order
codes = codes(idx);
% Calculate the average code length
avgLength = sum(cellfun(@length, codes) .* probabilities(idx));
end
function assignCodes(symbols, probabilities, start, endIdx, prefix, codes)
if start == endIdx
codes{start} = prefix;
else
mid = find(cumsum(probabilities(start:endIdx)) >= 0.5 * sum(probabilities(start:endIdx)), 1) + start - 1;
assignCodes(symbols, probabilities, start, mid, [prefix '0'], codes);
assignCodes(symbols, probabilities, mid+1, endIdx, [prefix '1'], codes);
end
end
```
### 4. 字符串编码
对样本字符串进行编码,并计算编码后的总长度。
```matlab
% Sample string
sampleString = 'AABCCDEFGH';
% Encode the sample string using Huffman and Shannon-Fano codes
[huffmanCodes, huffmanAvgLength] = huffmanCoding(Symbols, Probabilities);
[shannonFanoCodes, shannonFanoAvgLength] = shannonFanoCoding(Symbols, Probabilities);
% Function to encode a string using a given codebook
function encodedString = encodeString(str, codes)
encodedString = '';
for i = 1:length(str)
encodedString = [encodedString codes{strcmp(codes, str(i))}];
end
end
% Encode the sample string
huffmanEncodedString = encodeString(sampleString, huffmanCodes);
shannonFanoEncodedString = encodeString(sampleString, shannonFanoCodes);
% Calculate the total length of the encoded strings
huffmanTotalLength = length(huffmanEncodedString);
shannonFanoTotalLength = length(shannonFanoEncodedString);
% Display the results
disp(['Huffman Encoded String: ', huffmanEncodedString]);
disp(['Shannon-Fano Encoded String: ', shannonFanoEncodedString]);
disp(['Huffman Total Length: ', num2str(huffmanTotalLength)]);
disp(['Shannon-Fano Total Length: ', num2str(shannonFanoTotalLength)]);
```
### 5. 效率分析
计算并比较平均码长、压缩比、冗余度和编码效率。
```matlab
% Original size of the sample string
originalSize = length(sampleString) * ceil(log2(length(Symbols)));
% Compression ratio
huffmanCompressionRatio = originalSize / huffmanTotalLength;
shannonFanoCompressionRatio = originalSize / shannonFanoTotalLength;
% Redundancy
huffmanRedundancy = huffmanAvgLength - H;
shannonFanoRedundancy = shannonFanoAvgLength - H;
% Coding efficiency
huffmanEfficiency = (H / huffmanAvgLength) * 100;
shannonFanoEfficiency = (H / shannonFanoAvgLength) * 100;
% Display the results
disp(['Huffman Average Code Length: ', num2str(huffmanAvgLength)]);
disp(['Shannon-Fano Average Code Length: ', num2str(shannonFanoAvgLength)]);
disp(['Huffman Compression Ratio: ', num2str(huffmanCompressionRatio)]);
disp(['Shannon-Fano Compression Ratio: ', num2str(shannonFanoCompressionRatio)]);
disp(['Huffman Redundancy: ', num2str(huffmanRedundancy)]);
disp(['Shannon-Fano Redundancy: ', num2str(shannonFanoRedundancy)]);
disp(['Huffman Coding Efficiency: ', num2str(huffmanEfficiency), '%']);
disp(['Shannon-Fano Coding Efficiency: ', num2str(shannonFanoEfficiency), '%']);
```
### 6. 数学证明与分析
提供数学证明和可视化结果。
```matlab
% Function to plot the results
function plotResults(symbols, huffmanCodes, shannonFanoCodes, H, huffmanAvgLength, shannonFanoAvgLength, huffmanEfficiency, shannonFanoEfficiency)
figure;
subplot(2, 2, 1);
bar([cellfun(@length, huffmanCodes), cellfun(@length, shannonFanoCodes)]);
legend('Huffman', 'Shannon-Fano');
title('Code Lengths');
xlabel('Symbol');
ylabel('Code Length');
xticks(1:length(symbols));
xticklabels(symbols);
subplot(2, 2, 2);
bar([huffmanAvgLength, shannonFanoAvgLength]);
legend('Huffman', 'Shannon-Fano');
title('Average Code Length');
xlabel('Method');
ylabel('Average Code Length');
subplot(2, 2, 3);
bar([huffmanEfficiency, shannonFanoEfficiency]);
legend('Huffman', 'Shannon-Fano');
title('Coding Efficiency');
xlabel('Method');
ylabel('Efficiency (%)');
subplot(2, 2, 4);
bar([huffmanRedundancy, shannonFanoRedundancy]);
legend('Huffman', 'Shannon-Fano');
title('Redundancy');
xlabel('Method');
ylabel('Redundancy');
end
% Plot the results
plotResults(Symbols, huffmanCodes, shannonFanoCodes, H, huffmanAvgLength, shannonFanoAvgLength, huffmanEfficiency, shannonFanoEfficiency);
```
### 7. 输出呈现
展示生成的霍夫曼和香农-范诺码,以及各种指标的比较表。
```matlab
% Display the generated codes
disp('Huffman Codes:');
for i = 1:length(Symbols)
disp([Symbols{i}, ': ', huffmanCodes{i}]);
end
disp('Shannon-Fano Codes:');
for i = 1:length(Symbols)
disp([Symbols{i}, ': ', shannonFanoCodes{i}]);
end
% Create a table to compare the results
resultsTable = table({'Entropy'; 'Huffman Avg Length'; 'Shannon-Fano Avg Length'; 'Huffman Efficiency'; 'Shannon-Fano Efficiency'; 'Huffman Redundancy'; 'Shannon-Fano Redundancy'}, ...
{num2str(H); num2str(huffmanAvgLength); num2str(shannonFanoAvgLength); num2str(huffmanEfficiency); num2str(shannonFanoEfficiency); num2str(huffmanRedundancy); num2str(shannonFanoRedundancy)}, ...
'VariableNames', {'Metric', 'Value'});
disp(resultsTable);
```
### 提交指南
将上述代码保存为 `FirstnameLastname.mlx` 文件,并提交到Brightspace。同时,提交一个详细的PDF报告,总结你的发现、数学证明和结果。
希望这些代码和说明能帮助你顺利完成作业!如果有任何问题或需要进一步的帮助,请随时联系我。
阅读全文
相关推荐


















