energy detector in Matlab and plot ROC - matlab

I am having a issue with the ROC plot. I am not sure which part is wrong. I appreciate your help.
I am trying to create a Energy Detector Simulation using MATLAB. I have used a sinusoid as the input corrupted by AWGN.
clc
close all
clear all
%1. Generate a sinusoid
fs=30;
t=0:1/fs:10;
A=1;
f=10;
x=A*sin(2*pi*f*t);
figure;
plot(t,x)
%2. Generate a vector of noise samples with the required power.
N=1000;
snr_dB = -10; % SNR in decibels
snr = 10.^(snr_dB./10); % Linear Value of SNR
Pf = 0.01:0.01:1; % Pf = Probability of False Alarm
%3. Add signal and noise
Y = awgn(x,snr);
figure;
plot(t,Y)
%4. Simulation to plot Probability of Detection (Pd) vs. Probability of False Alarm (Pf)
for m = 1:length(Pf)
i = 0;
for kk=1:10000 % Number of Monte Carlo Simulations
energy = abs(Y).^2; % Energy of received signal
energy_fin =(1/N).*sum(energy); % Test Statistic for the energy detection
thresh(m) = (qfuncinv(Pf(m))./sqrt(N))+ 1; % Theoretical value of Threshold, refer, Sensing Throughput Tradeoff in Cognitive Radio, Y. C. Liang
if(energy_fin >= thresh(m)) % Check whether the received energy is greater than threshold, if so, increment Pd (Probability of detection) counter by 1
i = i+1;
end
end
Pd(m) = i/kk;
end
figure;
plot(Pf, Pd)
xlabel('Pf') % x-axis label
ylabel('Pd') % y-axis label
hold on
thresh = (qfuncinv(Pf)./sqrt(N))+ 1;
Pd_the = qfunc(((thresh - (snr + 1)).*sqrt(N))./(sqrt(2.*snr + 1)));
figure
plot(Pf, Pd_the, 'r')
xlabel('Pf') % x-axis label
ylabel('Pd threshold') % y-axis label
hold on

Related

Optical frequency comb time to frequency domain - MATLAB

I am trying to generate ultrashort pulses and then seeing the resulting frequency comb using a fourier transform, I have used the gaussian pulse and pulse train functions to try and do this but it is not coming out correctly - I am hoping to be able to change the variables at the top to see the changes quickly
If here is a solution or any good resources that could help me I would appreciate it alot... Thanks
Code is here:
fs = 1e17 ; % sample rate
frep = 7.5e9; % repition rate
f_sig = 1.93e15; %frequency of signal
tc = gauspuls('cutoff',f_sig,100,[],-80);
t = -tc*200:1/fs:tc*200;
[x1,x2,x3] = gauspuls(t,f_sig,0.5);
figure(1);
plot(t,x1,t,x3)
xlabel('Time (s)')
ylabel('Waveform')
ts = 0:1/fs/2:tc*50000000 ;
d = 0:1/frep:tc*50000000 ; %delay
y = pulstran(ts,d,x,fs);
figure(2);
plot(ts,y)
%Frequency Comb FFT
fsamp = fs;
L= length(t); %signal length
NFFT = 2^nextpow2(L);
FFT = abs(fftshift(fft(x3,NFFT))/NFFT); %FFT with FFTshift for both negative & positive frequencies
f = fsamp*(-NFFT/2:(NFFT/2-1))/NFFT; %Frequency Vector
figure(3)
plot(f/1e9,10*log10(FFT/1e-3));
title('Magnitude of FFT');
xlabel('Frequency (GHz)');
ylabel('Magnitude |X(f)|');
%xlim([-100 100])

Matlab FM Demodulation and Get Rid of Phase Folding Effect

I have a matlab code to Frequency modulation and demodulation a signal. My code is work well for modulation part. My message signal is m and modulated signal is u, code plot the message signal and its integral in one graph for plotting 1.
Then signal modulated with carrier and program plots the modulated signal in time domain for plotting 2.
After that, by the help of some code blocks program find the frequency spectrum of modulated signal and message signal to plot graph of them for plotting 3.
In demodulation part program make some fundamental calculation for FM detection, then to obtain message signal it uses filter.
Last part program plots the graph of recovered signal with message signal to compare them.
I summarized all code because ı do not know whre is the problem.
My problem about plotting 3 when I make zoom graph 3 I see some phase foldings or like it.Graph is not symmetric according to y-axis.
I did not solve this problem, I research about them and I decided to use unwrap(). Although I tried a lot, I could not be successful. How can I get rid of this phase folding with unwrap() function. Thank you.
My matlab code is ;
ts = 0.0001;% Sampling interval
t0 = 0.15; % Duration
t = 0:ts:t0;% define time vector
%% OTHER PARAMETERS
fc = 200; % Carrier signal frequency
kf =50; % Frequency deviation constant
fs = 1/ts; % Sampling frequency
%% MESSAGE SIGNAL SIMPLY
m = 1*(t<t0/3)-2*(t<2*t0/3).*(t>=t0/3);
%% Integration of m
int_m(1) = 0;
for k =1:length(m)-1
int_m(k+1) = int_m(k) + m(k)*ts;
end
%% PLOTTING 1
figure; subplot(211); % Message signal
plot(t,m);grid on;xlabel('time');ylabel('Amplitude');
title('m(t)');ylim([-3 2]);
subplot(212);plot(t,int_m);% Integral of message signal
grid on; xlabel('time');ylabel('Amplitude');title('integral of m(t)');
ylim([-0.07 0.07]);
%% FM MODULATED SIGNAL
u = cos(2*pi*fc*t + 2*pi*kf*int_m);
%% PLOTTING 2
figure; plot(t,u); % Modulated signal in time domain
grid on;xlabel('time');
ylabel('Amplitude');title('FM :u(t)');
ylim([-1.2 1.2]);
%% FINDING FREQUENCY SPECTRUM AND PLOTTING 3
% Frequency spectrum of m(t)
f=linspace(-1/(2*ts),1/(2*ts),length(t));
M=fftshift(fft(m))./length(t); % Taking fourier transform for m(t)
U=fftshift(fft(u))./length(t); % Taking fourier transform for u(t)
figure;subplot(211); % Frequence spectrum of m(t)
plot(f,abs(M)); grid;
xlabel('Frequency in Hz');xlim([-500 500]);
ylabel('Amplitude');title('Double sided Magnitude spectrum of m(t)');
subplot(212);plot(f,abs(U)); % Frequency spectrum of u(t)
grid;xlabel('Frequency in Hz');xlim([-500 500]);
ylabel('Amplitude');title('Double sided Magnitude spectrum of u(t)');
%% DEMODULATION (Using Differentiator)
dem = diff(u);
dem = [0,dem];
rect_dem = abs(dem);
%% Filtering out High Frequencies
N = 80; % Order of Filter
Wn = 1.e-2; % Pass Band Edge Frequency.
a = fir1(N,Wn);% Return Numerator of Low Pass FIR filter
b = 1; % Denominator of Low Pass FIR Filter
rec = filter(a,b,rect_dem);
%% Finding frequency Response of Signals
fl = length(t);
fl = 2^ceil(log2(fl));
f = (-fl/2:fl/2-1)/(fl*1.e-4);
mF = fftshift(fft(m,fl)); % Frequency Response of Message Signal
fmF = fftshift(fft(u,fl)); % Frequency Response of FM Signal
rect_demF = fftshift(fft(rect_dem,fl));% Frequency Response of Rectified FM Signal
recF = fftshift(fft(rec,fl)); % Frequency Response of Recovered Message Signal
%% PLOTTING 4
figure;subplot(211);plot(t,m);grid on;
xlabel('time');ylabel('Amplitude');
title('m(t)');ylim([-3 2]);
subplot(212);plot(t,rec);
title('Recovered Signal');xlabel('{\it t} (sec)');
ylabel('m(t)');grid;
My problem is in this third graph to show well I put big picture
k = -(length(X)-1)/2:1:length(X)/2;
Your k is not symmetric.
If you work with symmetric k is it working fine?

Plottng Error Vector Must Be Same Length

So I'm Having Trouble graphing this SSB signal after I modulated it. I keep getting the Vector Length error.
function SSB = SSBMOD
%Setting Up Variables
amplitude = 1; % Defining Amplitude
tau_in = 0.010; %Defining Tau
t_in = -0.010:0.0001:0.010; % Defining Time range
Fs = 27000; %Defining Carrier Frequency
Fc = cos(2*pi*Fs*t_in); %Carrier Signal
F = 1/t_in(end)*t_in*Fs*1.25; %Setting Up Frequency Vector for Graph
Sig = ProjectSig(amplitude,tau_in,t_in); %Calling Generated Signal output Function
%Modulating The signal Using SSB AM modulation
SSB = Sig.*Fc;
%Performing Fast Fourier Transform
SSBff = fft(SSB);
%Filter Signal to SSB
for k = 1000:1800
SSBff(k) = 0;
end
%Inverse Fourier Transform to Obtain SSB Signal
SSBSig = ifft(SSBff);
%Plotting Original Signal
subplot(3,3,1);
plot(t_in,Sig,'b');
axis([t_in(1) t_in(end) -1 1]);
title('Original Signal');
xlabel('Time (Sec)');
ylabel('V(t) (V)');
grid
shg
So right here below is the graph I'm having trouble with. I don't understand why My vector Lengths are off.
%Plotting SSB Signal
subplot(3,3,2);
plot(t_in,SSBSig,'b');
axis([t_in(1) t_in(end) -1 1]);
title('Single Sideband Signal');
xlabel('Time (Sec)');
ylabel('V(t) (V)');
grid
shg
end
t is only made up of 201 elements; setting SSBff(k) to zero from k = 1000 to 1800 increases the size of SSBff to 1800 elements. 1800 =/= 201. You should either increase your definition of t so you have more elements, or change what portions of SSBff you're setting to zero
As an aside, your for loop can also be called with the one line
SSBff(1000:1800) = 0;

How can I get the Resonant Frequencies (Bode plot)? (Response of 2-DOF System)

I want to study the response of the system.
I want to find the resonant frequency of the sprung mass (m1) and the resonant frequency of the unsprung mass (m2).
Because I am not sure if I have understood the meaning of resonant. Let's say that we have a suspension system and we stimulated with a step response 0.1(m).
That means, for example at 1(Hz) the sprung mass (m1) vibrating at the high level? and at 10(Hz) the unsprung mass (m2) vibrating at the high level?
I've read about bode plot and I did some things as you can see below but I don't know if this is the way to find the Resonant Frequencies. Maybe FFT is what I'm looking for?
In my bode plot (Picture below):
Blue Line: The first peak corresponds to the resonant frequency of the sprung mass (m1)? and Orange Line: Τhe second peak (which is higher than the first peak of orange line) corresponds to the resonant frequency of the unsprung mass (m2)?
If yes how can I get these values? What I need to add to my code?
Can I change the units from decibel to m?
clc;
clear all;
close all;
%% Parameters
m1 = 400; % Sprung Mass (kg)
m2 = 40; % Unsprung Mass (kg)
k1 = 21000; % Suspension Stiffness (N/m)
k2 = 150000; % Tire Stiffness (N/m)
b1 = 1500; % Suspension Damping (N*s/m)
b2 = 0; % Tire Damping Coefficient (N*s/m)
%% Transfer Function
num1 = [(0) (0) (b1*b2) (b1*k2+b2*k1) (k1*k2)];
den1 = [(m1*m2) (m1*b1+m1*b2+m2*b1) (m1*k1+m1*k2+m2*k1+b1*b2) (b1*k2+k1*b2) (k1*k2)];
G1 = tf(num1,den1); % G1(s) = X1(s)/Xr(s)
num2 = [(0) (m1*b2) (m1*k2+b1*b2) (b1*k2+b2*k1) (k1*k2)];
den2 = [(m1*m2) (m1*b1+m1*b2+m2*b1) (m1*k1+m1*k2+m2*k1+b1*b2) (b1*k2+k1*b2) (k1*k2)];
G2 = tf(num2,den2); % G2(s) = X2(s)/Xr(s)
%% Results
figure;
step(0.1*G1,0:0.01:5);
hold on;
step(0.1*G2,0:0.01:5);
title('');
legend('m1','m2');
xlabel('Time (s)');
ylabel('Amplitude (m)');
axis([]);
grid on;
figure;
bode(G1);
hold on;
bode(G2);
title('');
legend('m1','m2');
axis([]);
grid on;
Reaponse, Bode Plot and 2 DOF System

on the use and understanding of pwelch in matlab

I'm using the pwelch method in matlab to compute the power spectra for some wind speed measurements. So, far I have written the following code as an example:
t = 10800; % number of seconds in 3 hours
t = 1:t; % generate time vector
fs = 1; % sampling frequency (seconds)
A = 2; % amplitude
P = 1000; % period (seconds), the time it takes for the signal to repeat itself
f1 = 1/P; % number of cycles per second (i.e. how often the signal repeats itself every second).
y = A*sin(2*pi*f1*t); % signal
fh = figure(1);
set(fh,'color','white','Units', 'Inches', 'Position', [0,0,6,6],...
'PaperUnits', 'Inches', 'PaperSize', [6,6]);
[pxx, f] = pwelch(y,[],[],[],fs);
loglog(f,10*(pxx),'k','linewidth',1.2);
xlabel('log10(cycles per s)');
ylabel('Spectral Density (dB Hz^{-1})');
I cannot include the plot as I do not have enough reputation points
Does this make sense? I'm struggling with the idea of having noise at the right side of the plot. The signal which was decomposed was a sine wave with no noise, where does this noise come from? Does the fact that the values on the yaxis are negative suggest that those frequencies are negligible? Also, what would be the best way to write the units on the y axis if the wind speed is measured in m/s, can this be converted to something more meaningful for environmental scientists?
Your results are fine. dB can be confusing.
A linear plot will get a good view,
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
y = sin(2 * pi * 50 * t); % 50Hz signal
An fft approach,
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
subplot(1,2,1);
plot(f,2*abs(Y(1:NFFT/2+1)))
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
pwelch approach,
subplot(1,2,2);
[pxx, freq] = pwelch(y,[],[],[],Fs);
plot(freq,10*(pxx),'k','linewidth',1.2);
xlabel('Frequency (Hz)');
ylabel('Spectral Density (Hz^{-1})');
As you can see they both have peak at 50Hz.
Using loglog for both,
So "noise" is of 1e-6 and exists in fft as well, and can be ignored.
For your second question, I don't think the axis will change it will be frequency again. For Fs you should use the sampling frequency of wind speed, like if you have 10 samples of speed in one second your Fs is 10. Higher frequencies in your graph means more changes in wind speed and lower frequencies represent less changes for the speed.