# matlab - matlab向信号添加噪声的正确方法

``````
SNR = [-10:5:30]; %in Db

snr = 10. ^ (0.1. * SNR);

for I = 1:length(snr)

noise = 1/sqrt(2) * (randn(1, N) + 1i * randn(1, N));

u = y + noise. * snr(I);

end

``````

MATLAB或者 Octave (通信工具箱中) 有 awgn函数，可以添加( 高斯) 噪声，下面是代码( Octave 函数)的相关部分：

``````
if (meas == 1) % <-- if using signal power to determine appropriate noise power

p = sum( abs( x(:)). ^ 2)/length(x(:));

if (strcmp(type,"dB"))

p = 10 * log10(p);

endif

endif

if (strcmp(type,"linear"))

np = p/snr;

else % <-- in dB

np = p - snr;

endif

y = x + wgn (m, n, np, 1, seed, type, out);

``````

``````
y = awgn (x, snr, 'measured')

``````

``````
if (strcmp(type,"dBW"))

np = 10 ^ (p/10);

elseif (strcmp(type,"dBm"))

np = 10 ^((p - 30)/10);

elseif (strcmp(type,"linear"))

np = p;

endif

if(!isempty(seed))

randn("state",seed);

endif

if (strcmp(out,"complex"))

y = (sqrt(imp*np/2))*(randn(m,n)+1i*randn(m,n)); % imp=1 assuming impedance is 1 Ohm

else

y = (sqrt(imp*np))*randn(m,n);

endif

``````

``````
np = var(y,1); % linear scale

np = 10*log10(np); % in dB

``````

``````

sigLength = length(signal); % length

awgnNoise = randn(size(signal)); % orignal noise

pwrSig = sqrt(sum(signal.^2))/sigLength; % signal power

pwrNoise = sqrt(sum(awgnNoise.^2))/sigLength; % noise power

scaleFactor = (pwrSig/pwrNoise)/targetSNR; %find scale factor

awgnNoise = scaleFactor*awgnNoise;

out_signal = signal + awgnNoise; % add noise

``````

``````

sigLength = length(signal); % length

awgnNoise = randn(size(signal)); % orignal noise

pwrSig = sqrt(sum(signal.^2))/sigLength; % signal power

pwrNoise = sqrt(sum(awgnNoise.^2))/sigLength; % noise power

if targetSNR ~= 0

scaleFactor = (pwrSig/pwrNoise)/targetSNR; %find scale factor

awgnNoise = scaleFactor*awgnNoise;

out_signal = signal + awgnNoise; % add noise

else

out_signal = awgnNoise; % noise only

end

``````