Output of lti system in matlab doesn't look as expected - matlab

I have designed a low-pass filter with cut-off frequency at 4.82 kHz. The script below contains the transfer function, creates a periodic triangular pulse and passes it through the filter.
h=tf([8.06 *10^22],[1 9.801*10^4 4.803*10^9 1.455*10^14 2.723*10^18 2.549*10^22])
T = 10*(1/2000);
Fs = 80000;
dt = 1/Fs;
t = 0:dt:T-dt;
x = sawtooth(2*pi*2000*t,0.5);
lsim(h,x',t')
My question is: shouldn't the output also be a triangular pulse,since this is a linear system? If no,can someone explain to me theoritically why this is an accepted output? If yes, is there some adjustment to the code I can make to get the correct output?

No, an LTI real rational system necessarily smooths its input. You can convince yourself by thinking that in time domain an LTI system is a convolution operator. Alternatively, you can see that your system is a low-pass filter with roughly 6kHz bandwidth.
So you can multiply the frequency response of your system with the sawtooth spectrum to see what the answer would look like in the frequency domain.
Linearity is not a "shape" preserving property. It says if I get r1 as the response to i1 input signal and r2 to i2 then I will get 3*r1 + 5*r2 if I supply the input signal 3*i1 + 5*i2.
What you might be looking for is reference tracking for a control system that requires a controller to drive the system such that the difference between the input and the output is minimized.

Related

Filters performance analysis

I am working on some experimental data which, at some point, need to be time-integrated and then high-pass filtered (to remove low frequency disturbancies introduced by integration and unwanted DC component).
The aim of my work is not related to filtering, but still I would like to analyze more in detail the filters I am using to give some justification (for example to motivate why I chosed to use a 4th order filter instead of a higher/lower one).
This is the filter I am using:
delta_t = 1.53846e-04;
Fs = 1/delta_t;
cut_F = 8;
Wn = cut_F/(Fs/2);
ftype = 'high';
[b,a] = butter(4,Wn,ftype);
filtered_signal = filtfilt(b,a,signal);
I already had a look here: High-pass filtering in MATLAB to learn something about filters (I never had a course on signal processing) and I used
fvtool(b,a)
to see the impulse response, step response ecc. of the filter I have used.
The problem is that I do not know how to "read" these plots.
What do I have to look for?
How can I understand if a filter is good or not? (I do not have any specification about filter performances, I just know that the lowest frequency I can admit is 5 Hz)
What features of different filters are useful to be compared to motivate the choice?
I see you are starting your Uni DSP class on filters :)
First thing you need to remember is that Matlab can only simulate using finite values, so the results you see are technically all discrete. There are 4 things that will influence your filtering results(or tell you if your filter is good or bad) which you will learn about/have to consider while designing a Finite response filter:
1, the Type of the filter (i.e. Hamming, Butterworth (the one you are using), Blackman, Hanning .etc)
2, the number of filter Coefficients (which determines your filter resolution)
3, the sampling frequency of the original signal (ideally, if you have infinite sampling frequency, you can have perfect filters; not possible in Matlab due to reason above, but you can simulate its effect by setting it really high)
4, the cut-off frequency
You can play around with the 4 parameters so that your filter does what you want it to.
So here comes the theory:
There is a trade-off in terms of the width of your main lobe vs the spectrum leakage of your filter. The idea is that you have some signal with some frequencies, you want to filter out the unwanted (i.e. your DC noise) and keep the ones you want, but what if your desired signal frequency is so low that it is very close to the DC noise. If you have a badly designed filter, you will not be able to filter out the DC component. In order to design a good filter, you will need to find the optimal number for your filter coefficients, type of filter, even cut-off frequency to make sure your filter works as you wanted.
Here is a low-pass filter that I wrote back in the days, you can play around with filters a lot by filtering different kinds of signals and plotting the response.
N = 21; %number of filter coefficients
fc = 4000; %cut-off frequency
f_sampling = fs; %sampling freq
Fc = fc/f_sampling;
n = -(N-1)/2:(N-1)/2;
delta = [zeros(1,(N-1)/2) 1 zeros(1,(N-1)/2)];
h = delta - 2*Fc*sinc(2*n*Fc);
output = filter(h,1,yoursignal);
to plot the response, you want to plot your output in the frequency domain using DFT or FFT(in Matlab) and see how the signal has been distorted due to the leakage and etc.
NFFT=256; % FFT length
output=1/N*abs(fft(output,NFFT)).^2; % PSD estimate using FFT
this gives you what is known as a periodigram, when you plot, you might want to do the 10*log10 to it, so it looks nicer
Hope you do well in class.

How to pull out amplitude information from complex output of cpsd - MATLAB

I have two data sets that I want to analyze using a cross power spectral density plot in MATLAB with the function cpsd. With the complex output of cpsd, I was wondering how I can get amplitude information out of it. I know I can get phase info by angle(Pxy) but I don't know how to pull the amplitude information. Thanks
I think what you are looking for is abs(Pxy). According to the documentation, if Pxy = x + i*y, then:
abs(Pxy) = sqrt(x^2 + y^2) = sqrt(real(Pxy)^2 + imag(Pxy)^2)
Edit:
In light of your comment though, you are looking for the time-domain magnitude (not frequency domain, as the above will give you). This thread from the signal processing stack exchange may be of some help. It kind of looks like the averaging that cpsd performs eliminates the time-domain data from the signal.

How to implement a matched filter

I have a template. I compute the impulse response of the matched filter by taking the inverse Fourier Transform of the conjugate of the Fourier transform of my template. And I would like to perform the matched filtering operation on one of my available EEG channels using the 'filter' command in Matlab. Using the filter command the coefficient 'b' is my impulse response? Moreover, I would like to implement Matlab code to threshold the output of the matched filter to detect peaks.How can I achieve it?
Here is a start for you,
% A template is given
temp = randn(100,1);
% Create a matched filter based on the template
b = flipud(temp(:));
% For testing the matched filter, create a random signal which
% contains a match for the template at some time index
x = [randn(200,1); temp(:); randn(300,1)];
n = 1:length(x);
% Process the signal with the matched filter
y = filter(b,1,x);
% Set a detection threshold (exmaple used is 90% of template)
thresh = 0.9
% Compute normalizing factor
u = temp.'*temp;
% Find matches
matches = n(y>thresh*u);
% Plot the results
plot(n,y,'b', n(matches), y(matches), 'ro');
% Print the results to the console
display(matches);
As Andreas mentions in his answer, there is no need for the fourier transform. If you have a time-domain template, then its matched filter is simply a time-reversed version of itself (which I achieve with flipud). As you go along, you will find that there are many nuances to be worked out. This code works great because I am in control from start to finish, but once you start working with real data, things get much more complicated. Choosing an appropriate threshold value for example will require some knowledge about the data that you will be working with.
In truth, peak detection can be a very non-trivial task depending on the nature of your signals, etc. In my case, peak detection was easy because my signal was completely uncorrelated with the template, except at the point in the middle, and I also knew exactly what amplitude I was expecting to see. All of these assumptions are over-simplifications of the problem which I used to demonstrate the concepts.
Practically, you do this
y = filter( h, 1, x )
with h the impuse response and x and y input and output signals.
The matched filter is nothing else than a correlator that correlates with a given signal pattern.
It has a impulse response which is just the time reverse of the signal pattern you try to look for.
So by the way: If you have a measured signal pattern, reverse it and set this as impulse response of a FIR filter. There is no need to do this in the frequency domain if you have measurement in the time domain (both approaches are equivalent but one is more error prone then the other)

Time of Arrival estimation of a signal in Matlab

I want to estimate the time of arrival of GPR echo signals using Music algorithm in matlab, I am using the duality property of Fourier transform.
I am first applying FFT on the obtained signal and then passing these as parameters to pmusic function, i am still getting the result in frequency domain.?
Short Answer: You're using the wrong function here.
As far as I can tell Matlab's pmusic function returns the pseudospectrum of an input signal.
If you click on the pseudospectrum link, you'll see that the pseudospectrum of a signal lives in the frequency domain. In particular, look at the plot:
(from Matlab's documentation: Plotting Pseudospectrum Data)
Notice that the result is in the frequency domain.
Assuming that by GPR you mean Ground Penetrating Radar, then try radar or sonar echo detection approach to estimate the two way transit time.
This can be done and the theory has been published in several papers. See, for example, here:
STAR Channel Estimation in DS-CDMA Systems
That paper describes spatiotemporal estimation (i.e. estimation of both time and direction of arrival), but you can ignore the spatial part and just do temporal estimation if you have a single-antenna receiver.
You probably won't want to use Matlab's pmusic function directly. It's always quicker and easier to write these sorts of functions for yourself, so you know what is actually going on. In the case of MUSIC:
% Get noise subspace (where M is number of signals)
[E, D] = eig(Rxx);
[lambda, idx] = sort(diag(D), 'descend');
E = E(:, idx);
En = E(:,M+1:end);
% [Construct matrix S, whose columns are the vectors to search]
% Calculate MUSIC null spectrum and convert to dB
Z = 10*log10(sum(abs(S'*En).^2, 2));
You can use the Phased array system toolbox of MATLAB if you want to estimate the DOA using different algorithms using a single command. Such as for Root MUSIC it is phased.RootMUSICEstimator phased.ESPRITEstimator.
However as Harry mentioned its easy to write your own function, once you define the signal subspace and receive vector, you can directly apply it in the MUSIC function to find its peaks.
This is another good reference.
http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=1143830

Complex FFT then Inverse FFT MATLAB

I am using the FFT function in Matlab in an attempt to analyze the output of a Travelling Wave Laser Model.
The of the model is in the time domain in the form (real, imaginary), with the idea being to apply the FFT to the complex output, to obtain phase and amplitude information in the frequency domain:
%load time_domain field data
data = load('fft_data.asc');
% Calc total energy in the time domain
N = size(data,1);
dt = data(2,1) - data (1,1);
field_td = complex (data(:,4), data(:,5));
wavelength = 1550e-9;
df = 1/N/dt;
frequency = (1:N)*df;
dl = wavelength^2/3e8/N/dt;
lambda = -(1:N)*dl +wavelength + N*dl/2;
%Calc FFT
FT = fft(field_td);
FT = fftshift(FT);
counter=1;
phase=angle(FT);
amptry=abs(FT);
unwraptry=unwrap(phase);
Following the unwrapping, a best fit was applied to the phase in the region of interest, and then subtracted from the phase itself in an attempt to remove wavelength dependence of phase in the region of interest.
for i=1:N % correct phase and produce new IFFT input
bestfit(i)=1.679*(10^10)*lambda(i)-26160;
correctedphase(i)=unwraptry(i)-bestfit(i);
ReverseFFTinput(i)= complex(amptry(i)*cos(correctedphase(i)),amptry(i)*sin(correctedphase(i)));
end
Having performed the best fit manually, I now have the Inverse FFT input as shown above.
pleasework=ifft(ReverseFFTinput);
from which I can now extract the phase and amplitude information in the time domain:
newphasetime=angle(pleasework);
newamplitude=abs(pleasework);
However, although the output for the phase is greatly different compared to the input in the time domain
the amplitude of the corrected data seems to have varied little (if at all!),
despite the scaling of the phase. Physically speaking this does not seem correct, as my understanding is that removing wavelength dependence of phase should 'compress' the pulsed input i.e shorten pulse width but heighten peak.
My main question is whether I have failed to use the inverse FFT correctly, or the forward FFT or both, or is this something like a windowing or normalization issue?
Sorry for the long winded question! And thanks in advance.
You're actually seeing two effects.
First the expected one goes. You're talking about "removing wavelength dependence of phase". If you did exactly that - zeroed out the phase completely - you would actually get a slightly compressed peak.
What you actually do is that you add a linear function to the phase. This does not compress anything; it is a well-known transformation that is equivalent to shifting the peaks in time domain. Just a textbook property of the Fourier transform.
Then goes the unintended one. You convert the spectrum obtained with fft with fftshift for better display. Thus before using ifft to convert it back you need to apply ifftshift first. As you don't, the spectrum is effectively shifted in frequency domain. This results in your time domain phase being added a linear function of time, so the difference between the adjacent points which used to be near zero is now about pi.