QPSK constellation Diagram - matlab

Below is my MATLAB code for QPSK commnication:
clc;
clear all;
close all;
data=[0 1 0 1 1 1 0 0 1 1]; % information
%Number_of_bit=1024;
%data=randint(Number_of_bit,1);
figure(1)
stem(data, 'linewidth',3), grid on;
title(' Information before Transmiting ');
axis([ 0 11 0 1.5]);
data_NZR=2*data-1; % Data Represented at NZR form for QPSK modulation
s_p_data=reshape(data_NZR,2,length(data)/2); % S/P convertion of data
br=10.^6; %Let us transmission bit rate 1000000
f=br; % minimum carrier frequency
T=1/br; % bit duration
t=T/99:T/99:T; % Time vector for one bit information
% XXXXXXXXXXXXXXXXXXXXXXX QPSK modulation XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
y=[];
y_in=[];
y_qd=[];
for(i=1:length(data)/2)
y1=s_p_data(1,i)*cos(2*pi*f*t); % inphase component
y2=s_p_data(2,i)*sin(2*pi*f*t) ;% Quadrature component
y_in=[y_in y1]; % inphase signal vector
y_qd=[y_qd y2]; %quadrature signal vector
y=[y y1+y2]; % modulated signal vector
end
Tx_sig=y; % transmitting signal after modulation
tt=T/99:T/99:(T*length(data))/2;
figure(2)
subplot(3,1,1);
plot(tt,y_in,'linewidth',3), grid on;
title(' wave form for inphase component in QPSK modulation ');
xlabel('time(sec)');
ylabel(' amplitude(volt0');
subplot(3,1,2);
plot(tt,y_qd,'linewidth',3), grid on;
title(' wave form for Quadrature component in QPSK modulation ');
xlabel('time(sec)');
ylabel(' amplitude(volt0');
subplot(3,1,3);
plot(tt,Tx_sig,'r','linewidth',3), grid on;
title('QPSK modulated signal (sum of inphase and Quadrature phase signal)');
xlabel('time(sec)');
ylabel(' amplitude(volt0');
I am unable to understand which values to use to generate the phase constellation diagram for my code? What way in my code I can generate the correct phase constellation diagram?
============== UPDATE ==============
clc;
clear all;
close all;
data=[0 0 1 1 0 1 1 0 1 1 1 0]; % information
figure(1)
stem(data, 'linewidth',3), grid on;
title(' Information before Transmiting ');
axis([ 0 11 0 1.5]);
data_NZR=2*data-1; % Data Represented at NZR form for QPSK modulation
s_p_data=reshape(data_NZR,2,length(data)/2); % S/P convertion of data
br=10.^6; %Let us transmission bit rate 1000000
f=br; % minimum carrier frequency
T=1/br; % bit duration
t=T/99:T/99:T; % Time vector for one bit information
y=[];
y_in=[];
y_qd=[];
d=zeros(1,length(data)/2);
for i=1:length(data)/2
p=data(2*i);
imp=data(2*i - 1);
y1=s_p_data(1,i)*cos(2*pi*f*t); % inphase component
y2=s_p_data(2,i)*sin(2*pi*f*t) ;% Quadrature component
y_in=[y_in y1]; % inphase signal vector
y_qd=[y_qd y2]; %quadrature signal vector
y=[y y1+y2]; % modulated signal vector
if (imp == 0) && (p == 0)
d(i)=exp(j*pi/4);%45 degrees
end
if (imp == 1)&&(p == 0)
d(i)=exp(j*3*pi/4);%135 degrees
end
if (imp == 1)&&(p == 1)
d(i)=exp(j*5*pi/4);%225 degrees
end
if (imp == 0)&&(p == 1)
d(i)=exp(j*7*pi/4);%315 degrees
end
end
Tx_sig=y; % transmitting signal after modulation
qpsk=d;
tt=T/99:T/99:(T*length(data))/2;
figure(2)
subplot(3,1,1);
plot(tt,y_in,'linewidth',3), grid on;
title(' wave form for inphase component in QPSK modulation ');
xlabel('time(sec)');
ylabel(' amplitude(volt0');
subplot(3,1,2);
plot(tt,y_qd,'linewidth',3), grid on;
title(' wave form for Quadrature component in QPSK modulation ');
xlabel('time(sec)');
ylabel(' amplitude(volt0');
subplot(3,1,3);
plot(tt,Tx_sig,'r','linewidth',3), grid on;
title('QPSK modulated signal (sum of inphase and Quadrature phase signal)');
xlabel('time(sec)');
ylabel(' amplitude(volt0');
figure(3);
plot(d,'o');%plot constellation without noise
axis([-2 2 -2 2]);
grid on;
xlabel('real'); ylabel('imag');
title('QPSK constellation');

The QPSK symbol alphabet has four complex symbols. A set of random QPSK symbols can be created by generating an array of random integer numbers in 1..4 and mapping these numbers to complex symbols:
num_symbols = 1e4;
int_symbols = randi([1, 4], 1, num_symbols);
A = sqrt(2);
qpsk_symbols = zeros(size(int_symbols));
qpsk_symbols(int_symbols == 1) = A + 1i*A;
qpsk_symbols(int_symbols == 2) = A - 1i*A;
qpsk_symbols(int_symbols == 3) = - A + 1i*A;
qpsk_symbols(int_symbols == 4) = - A - 1i*A;
tx_sig = qpsk_symbols;
tx_sig could be the transmitted signal in a communication system. To plot the constellation diagram, use the real part as x-values and the imaginary part as y-values in the plot command. Additionally, use '.' as linestyle, so that every value is just represented by a dot, without line connections:
fh1 = figure;
plot_lims = [-3 3];
plot(real(qpsk_symbols), imag(qpsk_symbols), '.');
xlim(plot_lims);
ylim(plot_lims);
title('QPSK constellation without noise');
xlabel('real part');
ylabel('imaginary part');
This produces
which shows four distinct points. Adding noise makes this more interesting:
snr = 15; %// in dB
rx_sig = awgn(tx_sig, snr, 'measured');
fh2 = figure;
plot(real(rx_sig), imag(rx_sig), '.');
xlim(plot_lims);
ylim(plot_lims);
title(['QPSK constellation at an SNR of ' num2str(snr) ' dB']);
xlabel('real part');
ylabel('imaginary part');
which produces
This could be the received signal in a communications system neglecting inter-symbol interference and other frequency-selective components. (so-called AWGN channel for additive white gaussian noise).

Related

QPSK simulation with AWGN and BER/SER

I have a matlab code of QPSK simulation over baseband with AWGN noise, I'm calculating BER over each SNR value and plotting it along with
Theoretical BER.
When I'm generating SNR values in dB from 1 to 20 the code only computes simulated BER values from 0 to 10, why is this happening?
% QPSK MODULATION AND BER ESTIMATION IN AWGN CHANNEL
clc; clear all; close all;
N=1e6; % Number of bits transmited
SNRdB= 0:1:20; % SNR for simulation
SNRlin=10.^(SNRdB/10);
BER = zeros(1,length(SNRlin));% simulated BER
SER = zeros(1,length(SNRlin));% simulated SER
b1 = rand(1,N) > 0.5;
b2 = rand(1,N) > 0.5;
% QPSK symbol mapping
I = (2*b1) - 1;
Q = (2*b2) - 1;
S = I + 1j*Q;
N0 = 1./SNRlin; % Variance
for k = 1:length(SNRdB)
noise = sqrt(N0(k)/2)*(randn(1,N) + 1j*randn(1,N)); % AWGN noise
sig_Rx = S + noise; % Recived signal
% For BER calculation
sig_I = real(sig_Rx); % I component
sig_Q = imag(sig_Rx); % Q component
bld_I = sig_I > 0; % I decision
bld_Q = sig_Q > 0; % Q decision
b1_error = (bld_I ~= b1); % Inphase bit error
b2_error = (bld_Q ~= b2); % Quadrature bit error
Error_bit = sum(b1_error) + sum(b2_error); % Total bit error
BER(k) = sum(Error_bit)/(2*N); % Simulated BER
% For SER calculation
error_symbol = or(b1_error, b2_error); % if bit in I or bit in Q either wrong than error
SER(k) = sum(error_symbol)/N;
end
BER_theo = 2*qfunc(sqrt(2*SNRlin)); % Theoretical BER
SER_theo = 2*qfunc(sqrt(2*SNRlin)) - (qfunc(sqrt(2*SNRlin))).^2; % Theoretical SER
figure(1);
semilogy(SNRdB, BER_theo,'r-')
hold on
semilogy(SNRdB, BER,'k*')
xlabel('SNR[dB]')
ylabel('Bit Error Rate');
legend('Theoretical', 'Simulated');
title(['Probability of Bit Error for QPSK Modulation']);
grid on;
hold off;
figure(2);
semilogy(SNRdB, SER_theo,'r-')
hold on
semilogy(SNRdB, SER,'k*')
xlabel('SNR[dB]')
ylabel('Symbol Error Rate');
legend('Theoretical', 'Simulated');
title(['Probability of symbol Error for QPSK Modulation']);
grid on;
hold off;
Here is my output plot:
BER and SER simulation results

Plotting respiration signal in frequency domain on y axis while time is on x axis

I have a respiration (breathing) signal and a sampling frequency of 25 Hz and need to detect where is the lowest breathing frequency on a time scale, which should tell me actually when the person became sleepy. Fourier transforms in its classical form doesn't give me much useful information. So, to clarify: the time of measurement should be on the x-axis and the breathing frequency should be on the y-axis. Then, I suppose, lower amplitudes of the signal will show the slower breathing. What should be done with the signal to plot it the way I need?
All credits for this code go to Star Strider.
D = load('respiratory.txt');
Fs = 25; % Sampling Frequency (Hz)
Fn = Fs/2; % Nyquist Frequency
Ts = 1/Fs; % Sampling Time (sec)
L = numel(D);
t = linspace(0, L, L)*Ts; % Time Vector (sec)
figure(1)
plot(t, D)
grid
% axis([0 60 -850 -750])
axis([xlim -850 -750])
xlabel('Time')
ylabel('Amplitude')
FTD = fft(D-mean(D))/L; % Fourier Transform
Fv = linspace(0, 1, fix(L/2)+1)*Fn; % Frequency Vector
Iv = 1:numel(Fv); % Index Vector
figure(2)
plot(Fv, abs(FTD(Iv))*2)
grid
axis([0 2.5 ylim])
xlabel('Frequency (Hz)')
ylabel('Amplitude')
Wp = [0.35 0.65]/Fn; % Passband Frequency (Normalised)
Ws = [0.30 0.75]/Fn; % Stopband Frequency (Normalised)
Rp = 1; % Passband Ripple (dB)
Rs = 50; % Stopband Ripple (dB)
[n,Ws] = cheb2ord(Wp,Ws,Rp,Rs); % Filter Order
[z,p,k] = cheby2(n,Rs,Ws); % Filter Design, Sepcify Bandpass
[sos,g] = zp2sos(z,p,k); % Convert To Second-Order-Section For Stability
figure(3)
freqz(sos, 2^16, Fs) % Filter Bode Plot
D_filtered = filtfilt(sos, g, D); % Filter Signal
[pks,locs] = findpeaks(D_filtered, 'MinPeakDist',40);
figure(4)
plot(t, D_filtered)
hold on
plot(t(locs), pks, '^r')
hold off
grid
% axis([0 60 ylim])
axis([0 60 -15 15])
xlabel('Time')
ylabel('Amplitude')
tdif = diff([0 t(locs)]); % Time Difference Between Peaks (sec)
Dfrq = 60./tdif; % Frequency (Respirations/Minute)
figure(5)
plot(t(locs), Dfrq)
grid
axis([xlim 10 40])
xlabel('Time (sec)')
ylabel('Frequency (minute^{-1})')

energy detector in Matlab and plot ROC

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

SNR plot and rectangular fit (Matlab)

I have attached 3 images and the SNR function to calculate the SNR between each of the images. How can I plot this SNR so its easy to understand the levels from the plot rather than just numbers.
SNR function:
% function to calculate the drop in SNR between Best focussed image to
% slightly out of focus image. The value is presented in dB scale and amplitude
%for comparison.
% Terms:
%%Signal image = best focussed image
%%Noise image = slight off focussed image
%%Dark scan = for future reference with respect to Signal image
%---------------Define function to calcuate SNR---------------%
function SNR = SNR(signal, noise, typ, noisy)
% snr - calculate signal-to-noise ratio in decibel or amplitude
%
% Syntax: SNR = snr(signal, noise)
% SNR = snr(signal, signal_noise, typ, true)
%
% Inputs:
% signal - signal amplitude
% noise - noise amplitude or noisy signal
% typ - type of SNR (default:'db' to decibel or 'amp' to amplitude)
% noisy - eval noise flag (use noise as noisy signal)
%
% Outputs:
% SNR - Signal-to-Noise Ratio
%
% Example:
% dt = 0.01;
% T = 0:dt:10;
% sig = sin(2*pi*T);
% noisy = sig + (0 + .5 * randn(1,length(T))); % error mean 0 and sd .5
% snr_db = snr(sig,noisy,'db',true)
%
% Other m-files required: none
% Subfunctions: rms
%------------------------------- BEGIN CODE -------------------------------
if ~exist('typ', 'var')
typ = 'db';
end
if ~exist('noisy', 'var')
noisy = false;
end
if noisy % eval noise
noise = signal-noise;
end
if strcmp(typ,'db')
SNR = 20*log10(rms(signal)/rms(noise));
elseif strcmp(typ,'amp')% string comparison for type value.
SNR = rms(signal)/rms(noise);
end
end
%-------------------------------- END CODE --------------------------------
RMS function
function RMS= rms(varargin)
%
% Written by Phillip M. Feldman March 31, 2006
%
% rms computes the root-mean-square (RMS) of values supplied as a
% vector, matrix, or list of discrete values (scalars). If the input is
% a matrix, rms returns a row vector containing the RMS of each column.
% David Feldman proposed the following simpler function definition:
%
% RMS = sqrt(mean([varargin{:}].^2))
%
% With this definition, the function accepts ([1,2],[3,4]) as input,
% producing 2.7386 (this is the same result that one would get with
% input of (1,2,3,4). I'm not sure how the function should behave for
% input of ([1,2],[3,4]). Probably it should produce the vector
% [rms(1,3) rms(2,4)]. For the moment, however, my code simply produces
% an error message when the input is a list that contains one or more
% non-scalars.
if (nargin == 0)
error('Missing input.');
end
% Section 1: Restructure input to create x vector.
if (nargin == 1)
x= varargin{1};
else
for i= 1 : size(varargin,2)
if (prod(size(varargin{i})) ~= 1)
error(['When input is provided as a list, ' ...
'list elements must be scalar.']);
end
x(i)= varargin{i};
end
end
% Section 2: Compute RMS value of x.
RMS= sqrt (mean (x .^2) );
Script
% sig= best focussed image
% noisy= off focussed image
% dark = no light image
%-------------------------
% calculate SNR between:
% sig and noise
% signal and dark
% noise and dark
clear
sig = rgb2gray(imread('S1-BestFocus.bmp'));
noisy = rgb2gray(imread('S1-OffFocus.bmp'));
dark=rgb2gray(imread('DarkScan.bmp'));
sig_noise = SNR(sig,noisy,'db',true);
sig_dark = SNR(sig,dark,'db',true);
noise_dark = SNR(noisy,dark,'db',true);
Figures:
figures for calculation
I am imaging a slit of 15-18 microns in width and 1mm in length, the slit is not uniform, hence I have to check how much is the variation along the length of the slit in terms of width. What is the best possible way to get the measurement. ( one method is to use rectangular fit).

I want the convolution plot of f1 and f2 in the below program

In this code f1 and f2 are the Fourier Transform of Gate and Train of Impulse..
I need the plot of convolution between these two spectrums
I am expecting train of sinc function since convolution of a signal with train of impulse gives train of that func..
but using direct conv() I am getting a positive sine pulse...
fSampling = 10000; %Sampling Frequency
tSampling = 1/fSampling; %Sampling Time
L = 10000; %Length of Signal
to = (0:L-1)*tSampling; %Time Vector
F = 100;
% message signal
t = -5:0.01:5;
w=1;
a= rectpuls(t,2);
subplot(2,4,1);
plot(t,a);
xlabel('Time');
ylabel('Amplitude');
title('Message signal');
grid on;
% Fourier transform of sine wave
subplot(2,4,2)
NFFT = 2^nextpow2(L);
Xsig = fft(a,NFFT)/L;
f1 = fSampling/2*(linspace(0,1,NFFT/2+1));
plot(f1,2*abs(Xsig(1:NFFT/2+1)),'r');
grid on;
axis([-50 500 1.0000e-005 1])
title('\itSignle-Sided Amplitude Sepectrum of xsig(t)');
xlabel('\itFrequency(Hz) \rightarrow');
ylabel('|Xsig(f)| \rightarrow');
% train of impulse
n= -5:1:5;
l =length(n);
for i= 1:l
x(i)=1;
end;
subplot(2,4,3);
stem(n,x);
xlabel('Time');
ylabel('Amplitude');
title('Train of Impulses');
grid on;
% Fourier Transform of Train of Impulse
subplot(2,4,4)
NFFT = 2^nextpow2(L);
Xsig = fft(x,NFFT)/L;
f2 = fSampling/2*(linspace(0,1,NFFT/2+1));
stem(f2,2*abs(Xsig(1:NFFT/2+1)),'r');
grid on;
axis([-50 500 1.0000e-005 1])
title('\itSignle-Sided Amplitude Sepectrum of xsig(t)');
xlabel('\itFrequency(Hz) \rightarrow');
ylabel('|Xsig(f)| \rightarrow');
% multiplication of signals
T = -5:0.01:5;
b = a.*x(i);
subplot(2,4,5);
stem(T,b);
xlabel('Time');
ylabel('Amplitude');
title('Sampled signal');
grid on;
% Fourier transform of Sampled Signal
subplot(2,4,6)
NFFT = 2^nextpow2(L);
Xsig = fft(x,NFFT)/L;
f3 = fSampling/2*(linspace(0,1,NFFT/2+1));
plot(f3,2*abs(Xsig(1:NFFT/2+1)),'r');
grid on;
axis([-50 500 1.0000e-005 1])
title('\itSignle-Sided Amplitude Sepectrum of xsig(t)');
xlabel('\itFrequency(Hz) \rightarrow');
ylabel('|Xsig(f)| \rightarrow');
%Convolution of
c= conv(f1,f2)
subplot(2,4,7);
plot(c);
grid on;