MATLAB代码
% 参数设置
N = 4096; % 数据点数量
t = linspace(0, 2*pi, N); % 时间向量
width = 12; % 位宽% 正弦波
sine_wave = 2.5 * sin(t) + 2.5; % 幅度在0到5之间% 三角波
tri_wave = 5 - abs(mod(t/(2*pi)*4, 2) - 1);% 方波
square_wave = 2.5 * (square(t) + 1); % 将范围调整为0到5之间% 将波形数据保存为MIF文件
save_to_mif('sine_wave.mif', sine_wave, N, width);
save_to_mif('tri_wave.mif', tri_wave, N, width);
save_to_mif('square_wave.mif', square_wave, N, width);% 读取并绘制正弦波
sine_wave_data = read_mif('sine_wave.mif', N, width);
figure;
plot(sine_wave_data);
title('Sine Wave');
xlabel('Sample');
ylabel('Amplitude');% 读取并绘制三角波
tri_wave_data = read_mif('tri_wave.mif', N, width);
figure;
plot(tri_wave_data);
title('Triangle Wave');
xlabel('Sample');
ylabel('Amplitude');% 读取并绘制方波
square_wave_data = read_mif('square_wave.mif', N, width);
figure;
plot(square_wave_data);
title('Square Wave');
xlabel('Sample');
ylabel('Amplitude');% 函数:保存为MIF文件
function save_to_mif(filename, data, depth, width)% 打开文件fid = fopen(filename, 'w');% 写入头部信息fprintf(fid, 'DEPTH = %d;\n', depth);fprintf(fid, 'WIDTH = %d;\n', width);fprintf(fid, 'ADDRESS_RADIX = UNS;\n');fprintf(fid, 'DATA_RADIX = UNS;\n');fprintf(fid, 'CONTENT BEGIN\n');% 写入数据for i = 0:depth-1fprintf(fid, '%X : %X;\n', i, round(data(i+1) * (2^width - 1)));end% 写入结束fprintf(fid, 'END;\n');% 关闭文件fclose(fid);
end% 函数:从MIF文件中读取数据
function data = read_mif(filename, depth, width)% 打开MIF文件fid = fopen(filename, 'r');% 跳过文件头部信息,找到 "CONTENT BEGIN"while trueline = fgetl(fid);if contains(line, 'CONTENT BEGIN')break;endend% 初始化数据数组data = zeros(1, depth);% 读取数据部分for i = 1:depthline = fgetl(fid);% 解析地址和值tokens = regexp(line, '(\w+) : (\w+);', 'tokens');if ~isempty(tokens)addr = hex2dec(tokens{1}{1}); % 地址value = hex2dec(tokens{1}{2}); % 数据值data(addr + 1) = value / (2^width - 1); % 恢复原始的归一化数据endend% 关闭文件fclose(fid);
end
运行结果