Plotting different PSDs on MATLAB - 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!

Related

MATLAB: Linear Poisson Solver using iterative method

I am in the process of writing a 2D non-linear Poisson's solver. One intermediate test I performed is using my non-linear solver to solve for a "linear" Poisson equation. Unfortunately, my non-linear solver is giving me incorrect results, unlike if I try to solve it directly in MATLAB using the backslash ""
non-linear solver iteratively code: "incorrect results"
clearvars; clc; close all;
Nx = 20;
Ny = 20;
Lx = 2*pi;
x = (0:Nx-1)/Nx*2*pi; % x coordinate in Fourier, equally spaced grid
kx = fftshift(-Nx/2:Nx/2-1); % wave number vector
kx(kx==0) = 1; %helps with error: matrix ill scaled because of 0s
ygl = -cos(pi*(0:Ny)/Ny)'; %Gauss-Lobatto chebyshev points
%make mesh
[X,Y] = meshgrid(x,ygl);
%Chebyshev matrix:
VGL = cos(acos(ygl(:))*(0:Ny));
dVGL = diag(1./sqrt(1-ygl.^2))*sin(acos(ygl)*(0:Ny))*diag(0:Ny);
dVGL(1,:) = (-1).^(1:Ny+1).*(0:Ny).^2;
dVGL(Ny+1,:) = (0:Ny).^2;
%Diferentiation matrix for Gauss-Lobatto points
Dgl = dVGL/VGL;
D = Dgl; %first-order derivative matrix
D2 = Dgl*Dgl;
%linear Poisson solved iteratively
Igl = speye(Ny+1);
Ig = speye(Ny);
ZNy = diag([0 ones(1,Ny-1) 0]);
div_x_act_on_grad_x = -Igl; % must be multiplied with kx(m)^2 for each Fourier mode
div_y_act_on_grad_y = D * ZNy *D;
u = Y.^2 .* sin( (2*pi / Lx) * X);
uh = fft(u,[],2);
uold = ones(size(u));
uoldk = fft(uold,[],2);
max_iter = 500;
err_max = 1e-5; %change to 1e-8;
for iterations = 1:max_iter
for m = 1:length(kx)
L = div_x_act_on_grad_x * (kx(m)^2) + div_y_act_on_grad_y;
d2xk = div_x_act_on_grad_x * (kx(m)^2) * uoldk;
d2x = real(ifft(d2xk,[],2));
d2yk = div_y_act_on_grad_y *uoldk;
d2y = real(ifft(d2yk,[],2));
ffh = d2xk + d2yk;
phikmax_old = max(max(abs(uoldk)));
unewh(:,m) = L\(ffh(:,m));
end
phikmax = max(max(abs(unewh)));
if phikmax == 0 %norm(unewh,inf) == 0
it_error = err_max /2;
else
it_error = abs( phikmax - phikmax_old) / phikmax;
end
if it_error < err_max
break;
end
end
unew = real(ifft(unewh,[],2));
DEsol = unew - u;
figure
surf(X, Y, unew);
colorbar;
title('Numerical solution of \nabla^2 u = f');
figure
surf(X, Y, u);
colorbar;
title('Exact solution of \nabla^2 u = f');
Direct solver
ubar = Y.^2 .* sin( (2*pi / Lx) * X);
uh = fft(ubar,[],2);
for m = 1:length(kx)
L = div_x_act_on_grad_x * (kx(m)^2) + div_y_act_on_grad_y;
d2xk = div_x_act_on_grad_x * (kx(m)^2) * uh;
d2x = real(ifft(d2xk,[],2));
d2yk = div_y_act_on_grad_y *uh;
d2y = real(ifft(d2yk,[],2));
ffh = d2xk + d2yk;
%----------------
unewh(:,m) = L\(ffh(:,m));
end
How can I fix code 1 to get the same results as code 2?

FastICA Implementation.. Matlab

I have been working on a FastICA algorithm implementation using MatLab. Currently the code does not separate the signals as good as id like. I was wondering if anyone here could give me some advice on what I could do to fix this problem?
disp('*****Importing Signals*****');
s = [1,30000];
[m1,Fs1] = audioread('OSR_us_000_0034_8k.wav', s);
[f1,Fs2] = audioread('OSR_us_000_0017_8k.wav', s);
ss = size(f1,1);
n = 2;
disp('*****Mixing Signals*****');
A = randn(n,n); %developing mixing matrix
x = A*[m1';f1']; %A*x
m_x = sum(x, n)/ss; %mean of x
xx = x - repmat(m_x, 1, ss); %centering the matrix
c = cov(x');
sq = inv(sqrtm(c)); %whitening the data
x = c*xx;
D = diff(tanh(x)); %setting up newtons method
SD = diff(D);
disp('*****Generating Weighted Matrix*****');
w = randn(n,1); %Random weight vector
w = w/norm(w,2); %unit vector
w0 = randn(n,1);
w0 = w0/norm(w0,2); %unit vector
disp('*****Unmixing Signals*****');
while abs(abs(w0'*w)-1) > size(w,1)
w0 = w;
w = x*D(w'*x) - sum(SD'*(w'*x))*w; %perform ICA
w = w/norm(w, 2);
end
disp('*****Output After ICA*****');
sound(w'*x); % Supposed to be one of the original signals
subplot(4,1,1);plot(m1); title('Original Male Voice');
subplot(4,1,2);plot(f1); title('Original Female Voice');
subplot(4,1,4);plot(w'*x); title('Post ICA: Estimated Signal');
%figure;
%plot(z); title('Random Mixed Signal');
%figure;
%plot(100*(w'*x)); title('Post ICA: Estimated Signal');
Your covariance matrix c is 2 by 2, you cannot work with that. You have to mix your signal multiple times with random numbers to get anywhere, because you must have some signal (m1) common to different channels. I was unable to follow through your code for fast-ICA but here is a PCA example:
url = {'https://www.voiptroubleshooter.com/open_speech/american/OSR_us_000_0034_8k.wav';...
'https://www.voiptroubleshooter.com/open_speech/american/OSR_us_000_0017_8k.wav'};
%fs = 8000;
m1 = webread(url{1});
m1 = m1(1:30000);
f1 = webread(url{2});
f1 = f1(1:30000);
ss = size(f1,1);
n = 2;
disp('*****Mixing Signals*****');
A = randn(50,n); %developing mixing matrix
x = A*[m1';f1']; %A*x
[www,comp] = pca(x');
sound(comp(:,1)',8000)

Matlab: Confusion in Discrete time filter design

I have the following code in matlab:
L = 10000;
PN_30dB = -100; % dBc per Hz at 10k
f_offset = 5e6;
f_offset2 = 10e5;
F0 = 2.5e9;
A = 10^0.5;
Fs = 25e6;
fc1 = 100;
fc2 = 1e3;
fc3 = 10e3;
fc4 = 100e3;
fc5 = 1e6;
a1 = 2*pi*fc1/Fs;
a2 = 2*pi*fc2/Fs;
a3 = 2*pi*fc3/Fs;
a4 = 2*pi*fc4/Fs;
a5 = 2*pi*fc5/Fs;
sigma3 = (f_offset2/F0)*sqrt(2*10^(PN_30dB/10)/F0);
y1 = zeros(1,L);
y2 = zeros(1,L);
y3 = zeros(1,L);
y4 = zeros(1,L);
y5 = zeros(1,L);
y = zeros(1,L);
x = zeros(1,L);
for i = 2:L,
x(i) = sigma3*randn(1);
y1(i) = (1-a1)*y1(i-1) + a1*x(i);
y2(i) = (1-a2)*y2(i-1) + a2*x(i)/A;
y3(i) = (1-a3)*y3(i-1) + a3*x(i)/A^2;
y4(i) = (1-a4)*y4(i-1) + a4*x(i)/A^3;
y5(i) = (1-a5)*y5(i-1) + a5*x(i)/A^4;
y(i) = y1(i) + y2(i) + y3(i) + y4(i) + y5(i);
end
fft1 = fft(y);
fft1 = fft1(1:length(y)/2+1);
psd1 = (1/(F0*length(y)))*abs(fft1).^2;
psd1(2:end-1) = 2*psd1(2:end-1);
freq = 0:F0/length(y):F0/2;
figure(3);
semilogx(freq,10*log10(psd1))
grid on
acc = 0;
actual_timestamps_3 = zeros(1,L);
flicker = zeros(1,L);
for i = 1:L,
acc = acc + y(i);
actual_timestamps_3(i) = i/F0 + acc;
flicker(i) = acc;
end
fft1 = fft(2*pi*F0*flicker);
fft1 = fft1(1:length(flicker)/2+1);
psd1 = (1/(F0*length(flicker)))*abs(fft1).^2;
psd1(2:end-1) = 2*psd1(2:end-1);
freq = 0:F0/length(flicker):F0/2;
figure(4);
semilogx(freq,10*log10(psd1))
grid on
In this code, I am trying to create an output signal called flicker which should have a 30dB/dec roll-off of its power spectral density.
For that I am accumulating a signal called y(i) (in the second for loop) which has a 10dB/dec roll-off as can be seen in figure 3 inside the code. Since accumulation should add another 20db/dec, I am expecting the flicker signal to have a 30dB/dec roll off.
Signal y(i) is the output of a discrete time filter implemented in first for loop.
But I am not seeing the expected roll-off (30dB/dec) for the flicker signal (in figure 4). The plot shows only 20dB/dec for the flicker signal. Could someone please explain what I am doing wrong?
EDIT
Figure 4 in the code is shown below:
As you estimate the power spectral density with the FFT, you are looking at the data (flicker) which is effectively multiplied by a long rectangular window. This window introduces some spectral leakage, and unfortunately the decay of this spectral leakage for rectangular windows is less than 20dB/decade. The leakage from the stronger frequency components is thus masking the decay you are trying to observe.
To avoid this, you should multiply your signal by a different window function. There are plenty to experiment with (which offer different tradeoffs), but for illustration purposes you could use a blackman window with:
fft1 = fft(2*pi*F0*flicker .* blackman(length(flicker))');

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');

how to plot joint distribtuion of 2 random variable having 1000 data

here is the code i wrote to generate probability distribtuion of two random variable. now i would like to plot JPD.
clear all;
clc;
x1 = randn(1000,1);
x2 = 10*randn(1000,1);
[count_1, b] = hist(x1, 25); %25 bins
pd1 = count_1 / length(x1) / (b(2) - b(1)); % probability distribution function of x1
[count_2, bn] = hist(x2, 25); %25 bins
pd2 = count_2 / length(x2) / (bn(2) - bn(1)); % probabitlity distribtuion function of x2
%subplot(2,2,1), plot(x,s1)
%subplot(2,2,2),plot(x,s2)
%subplot(2,2,1),plot(b,pd1)
%subplot(2,2,2),plot(bn,pd2)
I am trying hard to get ans..plz any help out there..i have been tryihng over a month
Thanks..
I understand you don't have close form for your joint pdf, but "only the data". Using Matlab, you can indeed use this tool named hist3
% Generate random data
nData = 1e5;
data = zeros(2,nData);
m1 = 0; m2 = 1;
s1 = 1; s2 = 2;
for i=1:nData
d1 = m1+s1*randn;
d2 = m2+s2*randn;
data(:,i) = [d1; d2];
end
% hist3 will bin the data
xi = linspace(min(data(1,:)), max(data(1,:)), 50);
yi = linspace(min(data(2,:)), max(data(2,:)), 50);
hst = hist3(data,{xi yi}); %removed extra '
% normalize the histogram data
dx = xi(2)-xi(1);
dy = yi(2)-yi(1);
area = dx*dy;
pdfData = hst/sum(sum(hst))/area;
% plot pdf
figure(2); clf
contour(xi,yi,pdfData);
Hope this is of any help.