Code covered by the BSD License

# Formation of signal corrupted with noise

21 Jun 2012

Function forms a signal corrupted with noise and signal-to-noise ratio has a specified value

[s,varargout]=snrs(signal,noise,snr,varargin)
```function [s,varargout]=snrs(signal,noise,snr,varargin)
% S = SNRS(SIGNAL,NOISE,SNR) forms an array S of a signal that is corrupted
% with noise and signal-to-noise ratio has a specified value of SNR. SIGNAL
% is an array of input signal;  NOISE is an array of noise; it is
% considered that NOISE has the same sampling frequency as the sampling
% frequency of SIGNAL.  Both SIGNAL and NOISE should have floating point
% format. SNR is a signal-to-noise ratio, dB; S is an array of corrupted
% signal. Then, an array NOI of noise that has the same length as SIGNAL is
% built. NOI is formed by repetition of NOISE m times, where
% (m-1)*NUMEL(NOISE) < numel(SIGNAL) <= m*NUMEL(NOISE). If NUMEL(SIGNAL) =
% NUMEL(NOISE)), then NOI = NOISE. After multiplying NOI by appropriate
% coefficient NS a product to input signal is added. And it is an array S.
% S=SIGNAL+NOI*NS and SNR is signal-to-noise ratio of SIGNAL and NOI*NS. If
% length of NOISE less than length of SIGNAL we can change type of noise
% aggression. S = SNRS(SIGNAL,NOISE,SNR,1) apply noise only to the first
% NUMEL(NOISE) samples of SIGNAL.

% [S,STNR] = SNRS(...) returns STNR, which is signal-to-noise ratio of
% SIGNAL and NOI.
num=numel(signal);      %quantity of input signal samples
num1=numel(noise);      %quantity of noise samples
switch nargin
case 4
nm=min(num,num1);
noi=[noise,zeros(1,num-nm)]; %zero-padded array of a noise;
otherwise
m=ceil(num/num1);
noi=repmat(noise,m,1);  %array of a noise with length not less than num
noi=noi(1:num);         %array of a noise with length equals to num
end
sa=sqrt(sum(signal.^2));    %numerator of power ratio
sb=sqrt(sum(noi.^2));       %denominator of power ratio
varargout(1)={20*log10(sa/sb)}; %SNR of SIGNAL corrupted by NOI
ns=sa*10^(-snr/20)/sb;      %coefficient which is intended to get a specified SNR
s=noi*ns+signal;            %array of corrupted signal with a specified SNR
```