ODE with stochastic time dependent input - matlab

I am trying to repeat an example I found in a paper.
I have to solve this ODE:
25 a + 15 v + 330000 x = p(t)
where p(t) is a white noise sequence band-limited into the 10-25 Hz range; a is the acceleration, v is the velocity and x the displacement.
Then it says the system is simulated using a Runge-Kutta procedure. The sampling frequency is set to 1000 Hz and a Gaussian white noise is added to the data in such a way that the noise contributes to 5% of the signal r.m.s value (how do I use this last info?).
The main problem is related to the band-limited white noise. I followed the instructions I found here https://dsp.stackexchange.com/questions/9654/how-to-generate-band-limited-gaussian-white-noise and I wrote the following code:
% White noise excitation
% design FIR filter to filter noise in the range [10-25] Hz
Fs = 1000; % sampling frequency
% Time infos (for white noise)
T = 1/Fs;
tspan = 0:T:4; % I saw from the plots in the paper that the simulation last 4 seconds
tstart = tspan(1);
tend = tspan (end);
b = fir1(64, [10/(Fs/2) 25/(Fs/2)]);
% generate Gaussian (normally-distributed) white noise
noise = randn(length(tspan), 1);
% apply filter to yield bandlimited noise
p = filter(b,1,noise);
Now I have to define the function for the ode, but I do not know how to give it the p (white noise)...I tried this way:
function [y] = p(t)
b = fir1(64, [10/(Fs/2) 25/(Fs/2)]);
% generate Gaussian (normally-distributed) white noise
noise = randn(length(t), 1);
% apply filter to yield bandlimited noise
y = filter(b,1,noise);
end
odefun = #(t,u,m,k1,c,p)[u(2); 1/m*(-k1*u(1)-c*u(2)+p(t))];
[t,q,te,qe,ie] = ode45(#(t,u)odefun2(t,u,m,k2,c,#p),tspan,q0,options);
The fact is that the input excitation does not work properly: the natural frequency of the equation is around 14 Hz so I would expect to see the resonance in the response since the white noise is in the range 10-25 Hz.
I had a look at this Q/A also, but I can't still make it works:
How solve a system of ordinary differntial equation with time-dependent parameters
Solving an ODE when the function is given as discrete values -matlab-

Related

BPSK modulation and SNR : Matlab

Considering an Additive White Gaussian Noise (AWGN) communication channel where a signal taking values from BPSK modulation is being transmitted. Then, the received noisy signal is :y[k] = s[k] + w[k] where s[k] is either +1,-1 symbol and w[k] is the zero mean white gaussian noise.
-- I want to estimate the signal s and evaluate the performance by varing SNR from 0:40 dB. Let, the estimated signal be hat_s.
So, the graph for this would have on X axis the SNR range and on Y Axis the Mean Square Error obtained between the known signal values and the estimates i.e., s[k] - hat_s[k]
Question 1: How do I define signal-to-noise ratio? Would the formula of SNR be sigma^2/sigma^2_w. I am confused about the term in the numerator: what is the variance of the signal, sigma^2, usually considered?
Question 2: But, I don't know what the value of the variance of the noise is, so how does one add noise?
This is what I have done.
N = 100; %number of samples
s = 2*round(rand(N,1))-1;
%bpsk modulation
y = awgn(s,10,'measured'); %adding noise but I don't know
the variance of the signal and noise
%estimation using least squares
hat_s = y./s;
mse_s = ((s-hat_s).^2)/N;
Please correct me where wrong. Thank you.
First I think that it is important to know what are the things we have an a BPSK system:
The constellation of a BPSK system is [-A , A] in this case [-1,1]
the SNR will vary from 0 db to 40 db
I thing that the answer is in this function:
y = awgn( ... ); from matlab central:
y = awgn(x,snr) adds white Gaussian noise to the vector signal x. The
scalar snr specifies the signal-to-noise ratio per sample, in dB. If x
is complex, awgn adds complex noise. This syntax assumes that the
power of x is 0 dBW.
y = awgn(x,snr,sigpower) is the same as the syntax above, except that
sigpower is the power of x in dBW.
y = awgn(x,snr,'measured') is the same as y = awgn(x,snr), except that
awgn measures the power of x before adding noise.
you use y = awgn(x,snr,'measured'), so you do not need to worry, beacuse matlab carries all for you, measure the power of the signal, and then apply to channel a noise with the variance needed to get that SNR ratio.
let's see how can this happen
SNRbit = Eb/No = A^2/No = dmin^2 /4N0
the constelation [A,-A] in this case is [-1,1] so
10 log10(A^2/N0) = 10 log10(1/N0) = SNRbitdb
SNRlineal = 10^(0.1*SNRdb)
so with that:
noise_var=0.5/(EbN0_lin); % s^2=N0/2
and the signal will be something like this
y = s + sqrt(noise_var)*randn(1,size);
so in your case, I will generate the signal as you do:
>> N = 100; %number of samples
>> s = 2*round(rand(N,1))-1; %bpsk modulation
then prepare a SNR varies from 0 to 40 db
>> SNR_DB = 0:1:40;
after that calulating all the posible signals:
>> y = zeros(100,length(SNR_DB));
>> for i = 1:41
y(:,i) = awgn(s,SNR_DB(i),'measured');
end
at this point the best way to see the signal is using a constellation plot like this:
>> scatterplot(y(:,1));
>> scatterplot(y(:,41));
you can see a bad signal 0 db noise equal power as signal and a very good signal signal bigger than 40 DB noise. Eb/No = Power signal - Power noise db, so 0 means power noise equal to power of signal, 40 db means power of signal bigger bigger bigger than power of noise
then for you plot calculate the mse, matlab has one function for this
err = immse(X,Y) Description
example
err = immse(X,Y) calculates the mean-squared error (MSE) between the
arrays X and Y. X and Y can be arrays of any dimension, but must be of
the same size and class.
so with This:
>> for i = 1:41
err(i) = immse(s,y(:,i));
end
>> stem(SNR_DB,err)
For plots, and since we are working in db, it should be beeter to use logarithmic axes

How do I create band-limited (100-640 Hz) white Gaussian noise?

I would like to create 500 ms of band-limited (100-640 Hz) white Gaussian noise with a (relatively) flat frequency spectrum. The noise should be normally distributed with mean = ~0 and 99.7% of values between ± 2 (i.e. standard deviation = 2/3). My sample rate is 1280 Hz; thus, a new amplitude is generated for each frame.
duration = 500e-3;
rate = 1280;
amplitude = 2;
npoints = duration * rate;
noise = (amplitude/3)* randn( 1, npoints );
% Gaus distributed white noise; mean = ~0; 99.7% of amplitudes between ± 2.
time = (0:npoints-1) / rate
Could somebody please show me how to filter the signal for the desired result (i.e. 100-640 Hz)? In addition, I was hoping somebody could also show me how to generate a graph to illustrate that the frequency spectrum is indeed flat.
I intend on importing the waveform to Signal (CED) to output as a form of transcranial electrical stimulation.
The following is Matlab implementation of the method alluded to by "Some Guy" in a comment to your question.
% In frequency domain, white noise has constant amplitude but uniformly
% distributed random phase. We generate this here. Only half of the
% samples are generated here, the rest are computed later using the complex
% conjugate symmetry property of the FFT (of real signals).
X = [1; exp(i*2*pi*rand(npoints/2-1,1)); 1]; % X(1) and X(NFFT/2) must be real
% Identify the locations of frequency bins. These will be used to zero out
% the elements of X that are not in the desired band
freqbins = (0:npoints/2)'/npoints*rate;
% Zero out the frequency components outside the desired band
X(find((freqbins < 100) | (freqbins > 640))) = 0;
% Use the complex conjugate symmetry property of the FFT (for real signals) to
% generate the other half of the frequency-domain signal
X = [X; conj(flipud(X(2:end-1)))];
% IFFT to convert to time-domain
noise = real(ifft(X));
% Normalize such that 99.7% of the times signal lies between ±2
noise = 2*noise/prctile(noise, 99.7);
Statistical analysis of around a million samples generated using this method results in the following spectrum and distribution:
Firstly, the spectrum (using Welch method) is, as expected, flat in the band of interest:
Also, the distribution, estimated using histogram of the signal, matches the Gaussian PDF quite well.

Matlab, FFT frequency range differences or are they the same?

I'm trying to understand how the FFT in matlab works, particularly, how to define the frequency range to plot it. It happens that I have read from matlab help links and from other discussions here and I think (guess) that I'm confused about it.
In the matlab link:
http://es.mathworks.com/help/matlab/math/fast-fourier-transform-fft.html
they define such a frequency range as:
f = (0:n-1)*(fs/n)
with n and fs as:
n = 2^nextpow2(L); % Next power of 2 from length of signal x
fs = N/T; % N number of samples in x and T the total time of the recorded signal
But, on the other hand, in the previous post Understanding Matlab FFT example
(based on previous version of matlab), the resulting frequency range is defined as:
f = fs/2*linspace(0,1,NFFT/2+1);
with NFFT as the aforementioned n (Next power of 2 from length of signal x).
So, based on that, how these different vectors (equation 1 and final equation) could be the same?
If you can see, the vectors are different since the former has n points and the later has NFFT/2 points! In fact, the factor (fs/n) is different from fs/2.
So, based on that, how these different vectors (equation 1 and final equation) could be the same?
The example in the documentation from Mathworks plots the entire n-point output of the FFT. This covers the frequencies from 0 to nearly fs (exactly (n-1)/n * fs). They then make the following observation (valid for real inputs to the FFT):
The first half of the frequency range (from 0 to the Nyquist frequency fs/2) is sufficient to identify the component frequencies in the data, since the second half is just a reflection of the first half.
The other post you refer to just chooses to not show that redundant second half. It then uses half the number of points which also cover half the frequency range.
In fact, the factor (fs/n) is different from fs/2.
Perhaps the easiest way to make sense of it is to compare the output of the two expressions for some small value of n, says n=8 and setting fs=1 (since fs multiplies both expressions). On the one hand the output of the first expression [0:n-1]*(fs/n) would be:
0.000 0.125 0.250 0.500 0.625 0.750 0.875
whereas the output of fs/2*linspace(0,1,n/2+1) would be:
0.000 0.125 0.250 0.500
As you can see the set of frequencies are exactly the same up to Nyquist frequency fs/2.
The confusion is perhaps arising from the fact that the two examples which you have referenced are plotting results of the fft differently. Please refer to the code below for the references made in this explanation.
In the first example, the plot is of the power spectrum (periodogram) over the frequency range. Note, in the first plot, that the periodogram is not centered at 0, meaning that the frequency range appears to be twice that of the Nyquist sampling frequency. As mentioned in the mathworks link, it is common practice to center the periodogram at 0 to avoid this confusion (figure 2).
For the second example, taking the same parameters, the original plot is of amplitude of the fourier spectrum with a different normalization than in the first example (figure 3). Using the syntax of Matlab's full frequency ordering (as commented in the code), it is trivial to convert this seemingly different fft result to that of example 1; the identical result of the 0-centered periodogram is replicated in figure 4.
Thus, to answer your question specifically, the frequency ranges in both cases are the same, with the maximum frequency equal to the Nyquist sampling frequency as in:
f = fs/2*linspace(0,1,NFFT/2+1);
The key to understanding how the dfft works (also in Matlab) is to understand that you are simply performing a projection of your discrete data set into fourier space where what is returned by the fft() function in matlab are the coefficients of the expansion for each frequency component and the order of the coefficients is given (in Matlab as in example 2) by:
f = [f(1:end-1) -fliplr(f(1,2:end))];
See the Wikipedia page on the DFT for additional details:
https://en.wikipedia.org/wiki/Discrete_Fourier_transform
It might also be helpful for you to take the fft omitting the length as a power of 2 parameter as
y = fft(x).
In this case, you would see only a few non-zero components in y corresponding to the exact coefficients of your input signal. The mathworks page claims the following as a motivation for using or not using this length:
"Using a power of two for the transform length optimizes the FFT algorithm, though in practice there is usually little difference in execution time from using n = m."
%% First example:
% http://www.mathworks.com/help/matlab/math/fast-fourier-transform-fft.html
fs = 10; % Sample frequency (Hz)
t = 0:1/fs:10-1/fs; % 10 sec sample
x = (1.3)*sin(2*pi*15*t) ... % 15 Hz component
+ (1.7)*sin(2*pi*40*(t-2)); % 40 Hz component
% Removed the noise
m = length(x); % Window length
n = pow2(nextpow2(m)); % Transform length
y = fft(x,n); % DFT
f = (0:n-1)*(fs/n); % Frequency range
power = y.*conj(y)/n; % Power of the DFT
subplot(2,2,1)
plot(f,power,'-o')
xlabel('Frequency (Hz)')
ylabel('Power')
title('{\bf Periodogram}')
y0 = fftshift(y); % Rearrange y values
f0 = (-n/2:n/2-1)*(fs/n); % 0-centered frequency range
power0 = y0.*conj(y0)/n; % 0-centered power
subplot(2,2,2)
plot(f0,power0,'-o')
% plot(f0,sqrt_power0,'-o')
xlabel('Frequency (Hz)')
ylabel('Power')
title('{\bf 0-Centered Periodogram} Ex. 1')
%% Second example:
% http://stackoverflow.com/questions/10758315/understanding-matlab-fft-example
% Let's redefine the parameters for consistency between the two examples
Fs = fs; % Sampling frequency
% T = 1/Fs; % Sample time (not required)
L = m; % Length of signal
% t = (0:L-1)*T; % Time vector (as above)
% % Sum of a 3 Hz sinusoid and a 2 Hz sinusoid
% x = 0.7*sin(2*pi*3*t) + sin(2*pi*2*t); %(as above)
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
% NFFT == n (from above)
Y = fft(x,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
subplot(2,2,3)
plot(f,2*abs(Y(1:NFFT/2+1)),'-o')
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
% Get the 0-Centered Periodogram using the parameters of the second example
f = [f(1:end-1) -fliplr(f(1,2:end))]; % This is the frequency ordering used
% by the full fft in Matlab
power = (Y*L).*conj(Y*L)/NFFT;
% Rearrange for nicer plot
ToPlot = [f; power]; [~,ind] = sort(f);
ToPlot = ToPlot(:,ind);
subplot(2,2,4)
plot(ToPlot(1,:),ToPlot(2,:),'-o')
xlabel('Frequency (Hz)')
ylabel('Power')
title('{\bf 0-Centered Periodogram} Ex. 2')

Finding peak frequency in a complex signal using Matlab

I'm trying to find the peak frequency for two signals 'CA1' and 'PFC', within a specified range (25-140Hz).
In Matlab, so far I have plotted an FFT for each of these signals (see pictures below). These FFTs suggest that the peak frequency between 25-140Hz is different for each signal, but I would like to quantify this (e.g. CA1 peaks at 80Hz, whereas PFC peaks at 55Hz). However, I think the FFT is not smooth enough, so when I try and extract the peak frequencies it doesn't make sense as my code pulls out loads of values. I was only expecting a few values - one each time the FFT peaks (around 2Hz, 5Hz and ~60Hz).
I want to know, between 25-140Hz, what is the peak frequency in 'CA1' compared with 'PFC'. 'CA1' and 'PFC' are both 152401 x 7 matrices of EEG data, recorded
from 7 separate individuals. I want the MEAN peak frequency for each data set (i.e. averaged across the 7 test subjects for CA1 and PFC).
My code so far (based on Matlab help files and code I've scrabbled together online):
Fs = 508;
%notch filter
[b50,a50] = iirnotch(50/(Fs/2), (50/(Fs/2))/70);
CA1 = filtfilt(b50,a50,CA1);
PFC = filtfilt(b50,a50,PFC);
%FFT
L = length(CA1);
NFFT = 2^nextpow2(L);
%FFT for each of the 7 subjects
for i = 1:size(CA1,2);
CA1_FFT(:,i) = fft(CA1(:,i),NFFT)/L;
PFC_FFT(:,i) = fft(PFC(:,i),NFFT)/L;
end
%Average FFT across all 7 subjects - CA1
Mean_CA1_FFT = mean(CA1_FFT,2);
% Mean_CA1_FFT_abs = 2*abs(Mean_CA1_FFT(1:NFFT/2+1));
%Average FFT across all 7 subjects - PFC
Mean_PFC_FFT = mean(PFC_FFT,2);
% Mean_PFC_FFT_abs = 2*abs(Mean_PFC_FFT(1:NFFT/2+1));
f = Fs/2*linspace(0,1,NFFT/2+1);
%LEFT HAND SIDE FIGURE
plot(f,2*abs(Mean_CA1_FFT(1:NFFT/2+1)),'r');
set(gca,'ylim', [0 2]);
set(gca,'xlim', [0 200]);
[C,cInd] = sort(2*abs(Mean_CA1_FFT(1:NFFT/2+1)));
CFloor = 0.1; %CFloor is the minimum amplitude value (ignore small values)
Amplitudes_CA1 = C(C>=CFloor); %find all amplitudes above the CFloor
Frequencies_CA1 = f(cInd(1+end-numel(Amplitudes_CA1):end)); %frequency of the peaks
%RIGHT HAND SIDE FIGURE
figure;plot(f,2*abs(Mean_PFC_FFT(1:NFFT/2+1)),'r');
set(gca,'ylim', [0 2]);
set(gca,'xlim', [0 200]);
[P,pInd] = sort(2*abs(Mean_PFC_FFT(1:NFFT/2+1)));
PFloor = 0.1; %PFloor is the minimum amplitude value (ignore small values)
Amplitudes_PFC = P(P>=PFloor); %find all amplitudes above the PFloor
Frequencies_PFC = f(pInd(1+end-numel(Amplitudes_PFC):end)); %frequency of the peaks
Please help!! How do I calculate the 'major' peak frequencies from an FFT, and ignore all the 'minor' peaks (because the FFT is not smoothed).
FFTs assume that the signal has no trend (this is called a stationary signal), if it does then this will give a dominant frequency component at 0Hz as you have here. Try using the MATLAB function detrend, you may find this solves your problem.
Something along the lines of:
x = x - mean(x)
y = detrend(x, 'constant')

Chebyshev IIR FIlter: Got Coefficients, what next?

Here is my Matlab/Octave program
clc;
close all;
%BPF of pass 400-600Hz
fs1=300;
fp1=400;
fp2=600;
fs2=700;
samp=1500;
ap=1; %passband ripple
as=60; %stopband attenuation
%Normalizing the frequency
wp=[fp1 fp2]/(samp);
ws=[fs1 fs2]/(samp);
[N,wn]=cheb1ord_test(wp,ws,ap,as); %Generates order and cutoff parameters
[b,a]=cheby1(N,ap,wn); %Generates poles and zeros for the given order and cutoff
printf("b coeffs = %f\n",b);
printf("a coeffs = %f\n",a);
[H,W]=freqz(b,a,256);
plot(W/(2*pi),20*log10(abs(H))) %Transfer function works correctly, so coefficients are correct
%100 samples of 500hz
n = 1:100;
x=10*cos(2*pi*n*500*(1/samp));
printf("Order %d\n",N); %Depends on required ripple attenuation
figure;
subplot (2,1,1); plot(x);
y=filter(b,a,x); %**Apparently i suspect this does not work**
subplot (2,1,2); plot(y);
When i see the magnitude/frequency response, the graph is perfect and indicates 400 and 600 to be my filter cutoffs.
But however when i apply an input signal of 500Hz, i must expect to see the signal pass through the filter unharmed (as observed when i used Butterworth function), but the output is distorted and almost contains no signal
So i infer that my mistake is using the filter function to combine the chebyshev coefficients with the input signal.
If this is the problem, then how do i apply chebyshev coefficients to an input digital signal ?
For cheb1ord and cheby1 the frequencies are normalized between 0 and 1 with 1 corresponding to half the sampling frequency. You should get your wp and ws using
wp=[fp1 fp2]/(samp/2);
ws=[fs1 fs2]/(samp/2);
where samp is your sampling frequency.
I think the problem is with your x signal: I don't quite know what it is, but I can tell you what it is not and that's a 500Hz input signal.
I would define the time vector first and then apply the cos function (I assume you are sampling at 1500Hz):
f_input = 500; %Hz
t = 0:1/samp:1; % Time vector [0,1] sampled at 1500Hz
x = 10*cos(2*pi*t/f_input); % 500Hz input signal