clc; clear;%% 1. 信源 bits = randi([0,1],1,1000); % 生成随机的比特序列%% 2. 扩频% 生成Walsh函数 N = 8; walshMat = hadamard(N); walshSeq = walshMat(1,:);% 生成扩频码 spreadCode = repmat(walshSeq,1,length(bits)/N);% 扩频 spreadBits = bits.*spreadCode;%% 3. 信道% 添加高斯白噪声 SNRdB = 0:2:16; SNR = 10.^(SNRdB/10); for i = 1:length(SNR) noiseVar = 1/SNR(i); noise = sqrt(noiseVar)*randn(1,length(spreadBits)); channelOut = spreadBits + noise; %% 4. 解扩 % 解扩 despreadBits = channelOut./spreadCode; despreadBits(isnan(despreadBits)) = 0; %% 5. 信宿 % BPSK调制 modSignal = 1-2*despreadBits; % 接收滤波器 b = ones(1,N); a = 1; rxSignal = filter(b,a,modSignal); %% 6. BER-SNR曲线 % 计算误码率 err = sum(rxSignal<0) + sum(rxSignal>0); % 统计错误比特数 ber(i) = err/length(bits); % 计算误码率 % 绘制BER-SNR曲线 semilogy(SNRdB,ber,'-*'); xlabel('SNR(dB)'); ylabel('BER'); title('BER-SNR曲线'); grid on; hold on; ,优化代码
时间: 2024-04-27 20:19:54 浏览: 193
以下是优化后的代码:
clc;
clear;
%% 1. 信源
bits = randi([0,1],1,1000); % 生成随机的比特序列
%% 2. 扩频
% 生成Walsh函数
N = 8;
walshMat = hadamard(N);
walshSeq = walshMat(1,:);
% 生成扩频码
spreadCode = repmat(walshSeq,1,length(bits)/N);
% 扩频
spreadBits = bits.*spreadCode;
%% 3. 信道
% 添加高斯白噪声
SNRdB = 0:2:16;
SNR = 10.^(SNRdB/10);
for i = 1:length(SNR)
% 计算噪声方差
noiseVar = 1/SNR(i);
% 生成噪声
noise = sqrt(noiseVar)*randn(1,length(spreadBits));
% 信道传输
channelOut = spreadBits + noise;
%% 4. 解扩
% 解扩
despreadBits = channelOut./spreadCode;
despreadBits(isnan(despreadBits)) = 0;
%% 5. 信宿
% BPSK调制
modSignal = 1-2*despreadBits;
% 接收滤波器
b = ones(1,N);
a = 1;
rxSignal = filter(b,a,modSignal);
%% 6. BER-SNR曲线
% 计算误码率
err = sum(rxSignal~=bits); % 统计错误比特数
ber(i) = err/length(bits); % 计算误码率
end
% 绘制BER-SNR曲线
semilogy(SNRdB,ber,'-*');
xlabel('SNR(dB)');
ylabel('BER');
title('BER-SNR曲线');
grid on;
阅读全文