PAPR for psk with a rectangular pulse in Matlab - matlab

I generate a bpsk moudlation
N=1e4;
bits=randi([0,1],N,1);% наши биты
bpskModulator = comm.BPSKModulator;
bpskModulator.PhaseOffset = pi/16;
modData = bpskModulator(bits);
And a rectangle
Rc = 1e2; % [b/s] chip rate
T =1; % [s/b] inverse of chip rate
Tc = 0.5* T;
Fs = 2e2; % [Hz] sampling frequency
dt = 1/Fs; % [s]
ov1 = Fs/Rc; % sampling factor
sps = 10;
dt2=dt/sps;
t = [0:dt2:2*T]; % [s]
pulse_rect = rectpuls(t,T) ;
Now I want to make a bpsk convolution with a rectangle
n=upsample(modData,2);
signal1 = conv(pulse_rect,n);
signal=signal1';
My PAPR should come out equal to one, but when I count it's more than one. What am I doing wrong
pb = max(abs(signal));
avb = mean(abs(signal));
PAPR = pb/avb

Related

How do I find local threshold for coefficients in image compression using DWT in MATLAB

I'm trying to write an image compression script in MATLAB using multilayer 3D DWT(color image). along the way, I want to apply thresholding on coefficient matrices, both global and local thresholds.
I like to use the formula below to calculate my local threshold:
where sigma is variance and N is the number of elements.
Global thresholding works fine; but my problem is that the calculated local threshold is (most often!) greater than the maximum band coefficient, therefore no thresholding is applied.
Everything else works fine and I get a result too, but I suspect the local threshold is miscalculated. Also, the resulting image is larger than the original!
I'd appreciate any help on the correct way to calculate the local threshold, or if there's a pre-set MATLAB function.
here's an example output:
here's my code:
clear;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% COMPRESSION %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read base image
% dwt 3/5-L on base images
% quantize coeffs (local/global)
% count zero value-ed coeffs
% calculate mse/psnr
% save and show result
% read images
base = imread('circ.jpg');
fam = 'haar'; % wavelet family
lvl = 3; % wavelet depth
% set to 1 to apply global thr
thr_type = 0;
% global threshold value
gthr = 180;
% convert base to grayscale
%base = rgb2gray(base);
% apply dwt on base image
dc = wavedec3(base, lvl, fam);
% extract coeffs
ll_base = dc.dec{1};
lh_base = dc.dec{2};
hl_base = dc.dec{3};
hh_base = dc.dec{4};
ll_var = var(ll_base, 0);
lh_var = var(lh_base, 0);
hl_var = var(hl_base, 0);
hh_var = var(hh_base, 0);
% count number of elements
ll_n = numel(ll_base);
lh_n = numel(lh_base);
hl_n = numel(hl_base);
hh_n = numel(hh_base);
% find local threshold
ll_t = ll_var * (sqrt(2 * log2(ll_n)));
lh_t = lh_var * (sqrt(2 * log2(lh_n)));
hl_t = hl_var * (sqrt(2 * log2(hl_n)));
hh_t = hh_var * (sqrt(2 * log2(hh_n)));
% global
if thr_type == 1
ll_t = gthr; lh_t = gthr; hl_t = gthr; hh_t = gthr;
end
% count zero values in bands
ll_size = size(ll_base);
lh_size = size(lh_base);
hl_size = size(hl_base);
hh_size = size(hh_base);
% count zero values in new band matrices
ll_zeros = sum(ll_base==0,'all');
lh_zeros = sum(lh_base==0,'all');
hl_zeros = sum(hl_base==0,'all');
hh_zeros = sum(hh_base==0,'all');
% initiate new matrices
ll_new = zeros(ll_size);
lh_new = zeros(lh_size);
hl_new = zeros(lh_size);
hh_new = zeros(lh_size);
% apply thresholding on bands
% if new value < thr => 0
% otherwise, keep the previous value
for id=1:ll_size(1)
for idx=1:ll_size(2)
if ll_base(id,idx) < ll_t
ll_new(id,idx) = 0;
else
ll_new(id,idx) = ll_base(id,idx);
end
end
end
for id=1:lh_size(1)
for idx=1:lh_size(2)
if lh_base(id,idx) < lh_t
lh_new(id,idx) = 0;
else
lh_new(id,idx) = lh_base(id,idx);
end
end
end
for id=1:hl_size(1)
for idx=1:hl_size(2)
if hl_base(id,idx) < hl_t
hl_new(id,idx) = 0;
else
hl_new(id,idx) = hl_base(id,idx);
end
end
end
for id=1:hh_size(1)
for idx=1:hh_size(2)
if hh_base(id,idx) < hh_t
hh_new(id,idx) = 0;
else
hh_new(id,idx) = hh_base(id,idx);
end
end
end
% count zeros of the new matrices
ll_new_size = size(ll_new);
lh_new_size = size(lh_new);
hl_new_size = size(hl_new);
hh_new_size = size(hh_new);
% count number of zeros among new values
ll_new_zeros = sum(ll_new==0,'all');
lh_new_zeros = sum(lh_new==0,'all');
hl_new_zeros = sum(hl_new==0,'all');
hh_new_zeros = sum(hh_new==0,'all');
% set new band matrices
dc.dec{1} = ll_new;
dc.dec{2} = lh_new;
dc.dec{3} = hl_new;
dc.dec{4} = hh_new;
% count how many coeff. were thresholded
ll_zeros_diff = ll_new_zeros - ll_zeros;
lh_zeros_diff = lh_zeros - lh_new_zeros;
hl_zeros_diff = hl_zeros - hl_new_zeros;
hh_zeros_diff = hh_zeros - hh_new_zeros;
% show coeff. matrices vs. thresholded version
figure
colormap(gray);
subplot(2,4,1); imagesc(ll_base); title('LL');
subplot(2,4,2); imagesc(lh_base); title('LH');
subplot(2,4,3); imagesc(hl_base); title('HL');
subplot(2,4,4); imagesc(hh_base); title('HH');
subplot(2,4,5); imagesc(ll_new); title({'LL thr';ll_zeros_diff});
subplot(2,4,6); imagesc(lh_new); title({'LH thr';lh_zeros_diff});
subplot(2,4,7); imagesc(hl_new); title({'HL thr';hl_zeros_diff});
subplot(2,4,8); imagesc(hh_new); title({'HH thr';hh_zeros_diff});
% idwt to reconstruct compressed image
cmp = waverec3(dc);
cmp = uint8(cmp);
% calculate mse/psnr
D = abs(cmp - base) .^2;
mse = sum(D(:))/numel(base);
psnr = 10*log10(255*255/mse);
% show images and mse/psnr
figure
subplot(1,2,1);
imshow(base); title("Original"); axis square;
subplot(1,2,2);
imshow(cmp); colormap(gray); axis square;
msg = strcat("MSE: ", num2str(mse), " | PSNR: ", num2str(psnr));
title({"Compressed";msg});
% save image locally
imwrite(cmp, 'compressed.png');
I solved the question.
the sigma in the local threshold formula is not variance, it's the standard deviation. I applied these steps:
used stdfilt() std2() to find standard deviation of my coeff. matrices (thanks to #Rotem for pointing this out)
used numel() to count the number of elements in coeff. matrices
this is a summary of the process. it's the same for other bands (LH, HL, HH))
[c, s] = wavedec2(image, wname, level); %apply dwt
ll = appcoeff2(c, s, wname); %find LL
ll_std = std2(ll); %find standard deviation
ll_n = numel(ll); %find number of coeffs in LL
ll_t = ll_std * (sqrt(2 * log2(ll_n))); %local the formula
ll_new = ll .* double(ll > ll_t); %thresholding
replace the LL values in c in a for loop
reconstruct by applying IDWT using waverec2
this is a sample output:

Plotting different PSDs on MATLAB

So I am trying to plot on the same graph the PSD of the noise from an accelerometer and an IMU. The PSDs of the noise are:
Pacc = 10e-14 + 10e-18*f^-2; Pimu = 10e-12; with the frequency going from 10e-5 to 10Hz.
This is what I have now but I am not too sure on the result:
N = 1e6;
dt = 0.2;
PSD = 10e-12; %PSD of the IMU
sigma2 = PSD/dt; %PSD of WGN is PSD = sigma^2*dt
x = randn(N,1)*sqrt(sigma2);
xi = zeros(size(x));
xint(1) = x(1);
for n = 2:length(x)
xint(n) = (x(n)+x(n-1))/2*dt+xint(n-1);
end
NFFT = 1e5;
[px,~] = pwelch(x,hanning(NFFT),0.5,NFFT,1/dt,'twosided');
[pxint,f] = pwelch(xint,hanning(NFFT),0.5,NFFT,1/dt,'twosided');
Pacc = 10e-14 + 10e-18*f.^-2;
Pint = (2*pi*f).^(-1).*Pacc;
loglog(f,px)
hold on
loglog(f,Pint)
hold off
legend('noise IMU','noise Acc')
thank you for any help!

Create an iteration that picks n elements from array for calculations and increases by n for the next iteration

I have a matlab script that calculates the hourly thermal load of a refrigerated transport trailer for a day. The ambient temperature used is an array of hourly temperature data for a particular year, thus 8760x1 elements. I want create a for loop or some sort of iteration that picks every 24-hour data from the ambient temp array, thus 1:24, 25:48, etc; perform the calculations and store it in a matrix. So eventually it will result in a 24x365.
clc; clear; close all;
%%
load('Heerlen_TMY');
T_out = T2m(1:24);
T_in = zeros(length(T_out),1);
% T_in(:,1) = -18;
T_in(:,1) = 3;
% T_out(:,1) = 33;
RH = RH(1:24);
dT = (T_out - T_in);
%% Parameters
l_i = 13.36; w_i = 2.50; h_i = 2.50; % Trailer internal parameters
l_e = 13.54; w_e = 2.60; h_e = 2.75; % Trailer external parameters
m = zeros(length(T_out),1); %Initializing cargo mass
m_c = 20.0*1e3; % Total cargo mass[kg]
m_c = [m_c 0.87*m_c 0.75*m_c 0.62*m_c 0.5*m_c 0.37*m_c 0.25*m_c 0.12*m_c];
Delivery = [6 8 10 12 14 16 18 20]; % Delivery time during 24-hr period
On_road = [7 9 11 13 15 17 19 21]; % Driving times in a 24-hr period
m(Delivery)= m_c; % For product load during delivery
m(On_road) = m_c; % For calculating product load on road
%% Transmission load
K = 0.6; %0.4; %Overall heat transfer coefficient
S_i = ((l_i*w_i)+(l_i*h_i)+(w_i*h_i))*2; % Inner surface area;
S_e = ((l_e*w_e)+(l_e*h_e)+(w_e*h_e))*2; % Outer surface area;
S = sqrt(S_i*S_e);
deltaT = zeros(length(T_out),1);
deltaT(5) = dT(5);
deltaT(Delivery)= dT(Delivery); % For product load during delivery
deltaT(On_road) = dT(On_road);
Q_tr = K*S*deltaT.*1e-3;
Q_tr = abs(Q_tr)*1.23;
figure(1)
plot(Q_tr)
%% Precooling
V_a = l_i*w_i*h_i; % Volume payload [m^3]
rho_a = 1.27; % Density of air at 0 degrees [kg/m^3]
c_a = 1.005; % specific heat of air [kJ/kg/K]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Assuming initial temperature inside trailer = ambient temperature
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PreC = zeros(length(T_out),1); % Initializing precooling load
P = 3600; % Precooling duration
PreC(5) = P;
% Q_pre = (c_pt*V_pt*rho_pt + V_a*rho_a*c_a)*dT.*PreC./(3600*24);
Q_pre = (V_a*rho_a*c_a)*dT.*PreC./(3600);
figure(2); plot(Q_pre)
%% Product load
T1 = zeros(length(T_out),1);
T1(:,1) = 5; % Initial loading temperature of product
dT_pro = T1 - T_in;
h_r = 14.67; % heat of respiration [mW/kg]
c_l = 3.81; % Specific heat of dry drugs [kJ/kgK]
Q_pull = m.*c_l.*dT_pro; % loaded products to be cooled to setpoint temp
Q_resp = (h_r*m)./(1e6); % Load caused by chilled perishable products
Q_pro = Q_resp + (abs(Q_pull)./(3600*(length(Delivery)+length(On_road)+1)));
%% Infiltration load
W_d = 2.50; % Door width
H_d = 2.69; % Door height
D = [300 180]; % Loading and delivery duration
Theta_o = zeros(24,1);
Theta_o(Delivery) = D(2);
Theta_o(Delivery(1)) = D(1);
Theta_d = [1 0.25 0.5];
E = 0; % Effectiveness of doorway protective device
D_t = Theta_o/(3600* Theta_d(1));
%%%----------------------------------------------------
% Calculate sensible heat ratio Rs
%%%----------------------------------------------------
h = zeros(length(T_out),2);
y = h;
for k=1:numel(RH)
y(k,1) = Psychrometricsnew('phi',RH(k),'Tdb',T_out(k));
y(k,2) = Psychrometricsnew('phi',90,'Tdb',T_in(k));
end
%% Infiltration load - Method 1
D_f = zeros(length(T_in),1);
for n = 1:length(T_in)
if dT(n) >= 11
D_f1 = 0.5;
else
D_f1 = 0.8;
end
D_f(n)= D_f1;
% disp(D_f1)
end
%%%----------------------------------------------------
% Estimate sensible heat load of infiltration Qs/Ad
%%%----------------------------------------------------
Q_s = 4.5;
R_s = c_a*dT./((y(:,1) - y(:,2)).*1e-3);
q = 0.577*W_d*H_d^(1.5)*Q_s*(1./R_s);
%
Q_inf = q.*D_t.*D_f.*(1-E);
%% Method 2
rho_o = 1.205; rho_i = 1.275;
g = 9.81;
Enth = ((y(:,1) - y(:,2))./1e3);
Fm = (2/(1+(rho_i/rho_o)^(1/3)))^(1.5);
Q_inf_ = 0.221*W_d*H_d*rho_i*sqrt(1-(rho_o/rho_i))*...
sqrt(g*H_d)*Fm*(1-E);
Q_inf_1 = Q_inf_.*Enth.*D_f.*D_t;
%% Total load
% Q_pro = 0; %Q_inf = 0;
% Safety factor of 20% to account for
Q_tot = (Q_tr + Q_pre*1e-3 + Q_pro + Q_inf)*1.2;
Q_tot_1 = (Q_tr + Q_pre*1e-3 + Q_pro + Q_inf_1)*1.2;
% Q_tot = Q_tot*0.9;
figure()
plot(Q_tot)
hold on
plot(Q_tot_1)
As mimocha suggested in the comments, you just want to reshape your 8760x1 matrix of hourly temperatures into a 24x365 matrix, where each column contains the data for one day and each row contains the data for every hour within that day.
This is done by
A = reshape(input, [24, 465]);
where input is your 8760x1 matrix and A is the reshaped array of size 24x365.

Triangle Pulse with fourier transformation

I have a basic exercise for telecommunications with matlab, and i must plot a triangle pulse with (-c,0) to (c,0) with c = 6 and Amplitude = 1 in a for loop for M pulses and approach the periodic pulse using N Fourier series terms. I can't find something on the internet that can help me so far.
A similar code for rect pulse that I made and works is this:
a = 1;
b = 3;
N = 1000;
t = linspace(a-2*a,b+2*b,N);
A = 1;
y = rect_pulse(A,a,b,t);
plot(t,y);
grid on
axis([a-2*a b+2*b 0 2*A]);
M = 5;
T=7;
t_new = linspace(a-2*a,b+(M-1)*T+2*b,N);
y_new = zeros(1,N);
for index = 1:1:M
temp_y = rect_pulse(A,a+(index-1)*T,b+(index-1)*T,t_new);
y_new = y_new + temp_y;
end
figure;
plot(t_new,y_new);
grid on;
axis([a-2*a b+(M-1)*T+2*b 0 2*A]);
Where rect_pulse is this:
function y = rect_pulse (A,a,b,t)
N=length(t);
y = zeros(1,N);
for index = 1:1:N
if(t(1,index)>=a) && (t(1,index)<=b)
y(1,index) = A;
end
end
And fourier series is this:
function y_fourier = fourier_series_rect_pulse(a,b,To,N,t)
y_fourier = 0;
wo = (2*pi)/To;
for n = -N:1:N
f_real = #(x) cos(n*wo*x);
f_imag = #(x) sin(n*wo*x);
cn = (1/To)*(quad(f_real,a,b)) - j*quad(f_imag,a,b));
y_fourier = y_fourier + cn*exp(j*n*wo*t);
end
y_fourier = real(y_fourier);
Any ideas how to make this in to triangle pulse?
This probably deviates significantly from your approach but if you're curious here is a script I came up with to generate a triangular pulse train that can be adjusted. This method, unfortunately, uses the fft() function which may or may not be off-limits in your case. Most of the script uses indexing and manipulating vectors. Additional spectral components may be seen due to the DC offset of the alternating triangular wave and the limited number of cycles available in the vector representation of the triangular wave.
Triangular Pulses and Fourier Transforms:
Triangular Pulse with Duty-Off Period:
Higher frequency spectral components present due to the abrupt corners that occur at the transition states of the triangle pulse and duty-off period.
%******************************************************%
%PROPERTIES THAT CAN BE CHANGED%
%******************************************************%
Plotting_Interval = 0.01; %0.01 seconds%
Pulse_Width = 1/20; %6 seconds%
Period = 1/20; %10 seconds (should be at least the pulse width)%
Start_Time = 0;
End_Time = Pulse_Width*1000; %(1000 pulses)%
%******************************************************%
if(Period < Pulse_Width)
Period = Pulse_Width;
end
Time_Vector = (Start_Time: Plotting_Interval: End_Time);
Points_Per_Unit_Time = 1/Plotting_Interval;
Half_Pulse = Pulse_Width/2;
Number_Of_Points = Pulse_Width/Plotting_Interval;
Rising_Slope = linspace(0,1,floor(Number_Of_Points/2) + 1);
Falling_Slope = 1 - Rising_Slope;
Triangular_Pulse = [Rising_Slope Falling_Slope(2:end)];
t = (0: Plotting_Interval: Pulse_Width);
Periodic_Triangular_Pulse = zeros(1,length(Time_Vector));
for Cycle = 1: +Period/Plotting_Interval: End_Time/Plotting_Interval
Periodic_Triangular_Pulse(1,Cycle:Cycle+length(Triangular_Pulse)-1) = Triangular_Pulse(1,1:end);
end
Periodic_Triangular_Pulse = Periodic_Triangular_Pulse(1,1:length(Time_Vector));
subplot(1,2,1); plot(Time_Vector,Periodic_Triangular_Pulse);
Triangle_Frequency = 1/Period;
title("Triangular Pulse Train " + num2str(Triangle_Frequency) + "Hz (first 10 cycles)");
axis([0 Period*10 0 1]);
xlabel("Time (s)"); ylabel("Amplitude");
Signal_Length = length(Periodic_Triangular_Pulse);
Fourier_Transform = fft(Periodic_Triangular_Pulse);
Fs = 1/Plotting_Interval;
P2 = abs(Fourier_Transform/Signal_Length);
P1 = P2(1:floor(Signal_Length/2)+1);
P1(2:end-1) = 2*P1(2:end-1);
f = Fs*(0:(Signal_Length/2))/Signal_Length;
subplot(1,2,2); plot(f,P1)
title("Single-Sided Fourier Transform");
xlabel("Frequency (Hz)"); ylabel("Magnitude");
Ran using MATLAB R2019b

Solving ring laser equations in MATLAB using ode

I have written a Matlab code which is a simulation of NOT gate implementation using ring lasers. Si variable is input in my code. But my code works only for Si = 0. for any other non zero value it doesn't show output.
%-----------Rate Equation MATLAB code ---------
function dydt = requations(t,y)
dydt = zeros(size(y));
%prompt = 'Sinput???';
%Si = input(prompt);
Si = 0; %MY INPUT
q = 1.6e-19; % charge of electron
tau_e = 1e-9; % carrier lifetime
No = 3.3e18; % # No of carriers at transparency
a = 1e-15; % Linear gain coefficient
Vg = 7.5e9; % group velocity
Vp = 3e-11; %Photon reservoir volume
V = 1e-11; %Carrier reservoir Volume
tau_p = 1.7e-12; % photon lifetime
beta = 1e-5; % spontateous emission coefficient
eps = 7.5e-17; % Nonlinear gain suppression coefficient
Ni = 0.8; %Internal quantum efficiency
w = 2*pi*10e5;
Io = 10e-3;
%I = Io*sin(w*t);
I = 2.5*Io; %for test purposes
tp = 1/tau_p;
te = 1/tau_e;
Aint = 6; %Internal losses inside cavity waveguides
%G = ((a/Vp)* (N-(V*No)))/(1-eps*(Sc + Scc));
alpha = -2; %alpha factor
L = 76e-4 ;%size of the ring
wcb = 2*pi*70;
%R = 0.25;
Wcb = wcb*1000000;
%r = 1/R;
tpcw = Vg*(Aint + ((1/L)*log(4)));
Tpcw = 1/tpcw;
%------Rate equations-------
N = y(1);
Sc = y(2); %Clock wise photon number
yc = y(3);
Scc = y(4); %anti clockwise photon number
ycc = y(5);
G = ((a/Vp)* (N-(V*No)))/(1-eps*(Sc + Scc));
dydt(1) = (Ni*I)/q - y(1)*te - Vg*G*(y(2) + y(4)); %dN/dt
dydt(2) = (Vg*G-Tpcw)*y(2) + beta*y(1)*te; %dSc/dt
dydt(3) = -(alpha/2)*(Vg*G-Tpcw); %dyc/dt
dydt(4) = (Vg*G-Tpcw)*y(4) + beta*y(1)*te + ((2*Vg)/L)*cos(y(5))*(sqrt(Si*y(4))); %dScc/dt
dydt(5) = -Wcb - ((alpha/2)*(Vg*G-Tpcw)) - ((Vg/L)*sin(y(5))*(sqrt(Si/y(4)))); %dycc/dt
Below is the Ode file
%------Rate equations for requation file------
format bank;
close all;
clear all;
clc;
%time interval
ti=0;
tf=200;
tspan=[ti tf];
x0 = [3.75e7, 2.25e6, 0, 2.25e6, 0]; %initial vectors
%options= odeset('RelTol',100, 'AbsTol',[3.75e7, 2.25e6]);
[t,y]= ode23t(#requations,tspan,x0);
%Plotting the graphs:
figure
subplot(5,1,1), plot(t,y(:,1),'r'),grid on;
title('Laserrate equations'),ylabel('N');
subplot(5,1,2), plot(t,y(:,2),'b'),grid on;
ylabel('Scw'); xlabel('t');
subplot(5,1,3), plot(t,y(:,3),'g'),grid on;
ylabel('ycw');xlabel('t');
subplot(5,1,4), plot(t,y(:,3),'g'),grid on;
ylabel('Sccw');xlabel('t');
subplot(5,1,5), plot(t,y(:,3),'g'),grid on;
ylabel('yccw');xlabel('t');