DFT of time domain for step function - matlab

I have been working on DFT in Matlab recently, here is my code in Matlab. which part of my code has problem, my sampling is wrong??? I'll be grateful if you answer my question:
dt = 0.01; %sampling time interval
Fs = 1/dt; %sampling rate
t = 0:dt:45; %Time vector
t0 = 5; %duration of applied stress
N = length(t); %number of sample points
y_timedomain = heaviside(t)-heaviside(t-t0); %the step function
figure (1)
plot(y_timedomain)
axis([-100,1000,-0.2,1.2]);
y_freqDomain=abs(fft(y_timedomain)); % fft of step funcion, y(t)
z = fftshift(y_freqDomain); % DFT and shift center to zero
figure (2)
plot(linspace(-10,10,length(y_freqDomain)),z)
xlabel('Sample Number')
ylabel('Amplitude')
title('Using the Matlab fft command')
grid
axis([-.3,.3,0,1000]);
meanwhile, I have 2 question about this code:
1- my step function at 0 time, has magnitude of 1/2, but i want my step function at 0 time be 0 instead of 1/2,( such as rectangle shape), but i don't know how to correct it???
2- when we do DFT, should we use "shift FFT" always????
if you give me your advice about this code i will be really thankful.

Heaviside Step Function
MATLAB does define the step function with 1/2 for x=0 (see http://de.mathworks.com/help/symbolic/heaviside.html?refresh=true), if you wish otherwise you could define your own function, maybe like this here?
mystep = #(x) sign(max(x, 0));
fftshift
No you don't have to use fftshift always, that really depends on what exactly you want to do. In principle, the fft is not very suited for signals like the step function (if you want to do some frequency analysis, in that particular case, I recommend to do analytical ft!). There are many side effects (I don't want to go into that field right now) and fftshift is one of the tools to help deal with those. Read the doc (doc fftshift) and learn more about the ft in general.

Related

How to use the FFT (Fast Fourier Transform) in Matlab

I'm just learning Matlab and the fast fourier transform algorithm.
As a first step I tried to duplicate this example: https://en.wikipedia.org/wiki/Fourier_transform#Example
I use the following code:
t = -6:0.01:6;
s = cos(2 * pi * 3 * t) .* exp(-pi * t.^2);
figure(1);
plot(t, s);
xlim([-2 2]);
r = fft(s);
figure(2);
plot(t, abs(r));
And I obtained the following picture:
Figure 2:
Figure 1 is OK, but Figure 2 is not. I see one of the problem is that in Figure 2 I should plot vector r against frequency, not against time. Another problem in Figure 2 is the scale in the Y-axis.
Thus, I have 2 questions in order to duplicate the example:
How can I obtain the frequency domain (X-axis in Figure 2)?
How should I scale vector r (Y-axis in Figure 2)?
Your issue is that you aren't actually creating a frequency vector to plot the fft against. The reason that the fft is plotted against time is because that is what you specified in your plot command.
Here is a working fft outline:
N=length(t);
index=0:N-1;
FrequencyResolution=SamplingRate/N;
Frequency=index.*FrequencyResolution;
data_fft=fft(detrend(data));
%the detrend isn't necessary but it does look nicer because it focuses the plot on changes around the mean of the data
data_FFTmagnitude=abs(data_fft);
plot(Frequency, data_FFTmagnitude)
I remember once for the first time that I wanted to use DFT and FFT for one of my study projects I used this webpage, it explains in detail with examples on how to do so. I suggest you go through it and try to replicate for your case, doing so will give you insight and better understanding of the way one can use FFt as you said you are new to Matlab. Do not hesitate to ask again if you need more detailed help.
And also keep in mind that for FFT it is better to have signal length of a power of 2, that way you will get the most exact results, and if you cannot control your signal length you can take the largest power of 2 close to that length, as everyone usually does.

Finding the phase from FFT on MATLAB

I know the fundamental frequency of my signal and therefore I also know the other frequencies for the harmonics, I have used the FFT command to compute the first 5 harmonics (for which I know their frequencies). Is it possible for me to find the phase with this available information?
Please note I cant be sure my signal is only one period and therefore need to calculate the phase via the known frequency values.
Code seems to be working:
L = length(te(1,:)); % Length of signal
x = te(1,:);
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(x,NFFT)/L;
f = linspace(1,5,5);
Y(1) = []; % First Value is a sum of all harmonics
figure(1);
bar(f,2*abs(Y(1:5)), 'red')
title('Transmission Error Harmonics')
xlabel('Harmonic')
ylabel('|Y(f)|')
figure(2);
bar(f,(angle(Y(1:5))))
title('Transmission Error Phase')
xlabel('Harminic')
ylabel('Angle (radians)')
Note that if your fundamental frequency is not exactly integer periodic in the fft length, then the resulting phase (atan2(xi,xr)) will be flipping signs between adjacent bins due to the discontinuity between the fft ends (or due to the rectangular window convolution), making phase interpolation interesting. So you may want to re-reference the FFT phase estimation to the center of the data window by doing an fftshift (pre, by shift/rotating elements, or post, by flipping signs in the fft result), making phase interpolation look more reasonable.
In general your Fourier transformed is complex. So if you want to know the phase of a certain frequency you calculate it with tan(ImaginaryPart(Sample)/RealPart(Sample)). This can be done by using angle().
In your case you
1- calculate fft()
2- calculate angle() for all samples of the FFT or for the samples you are interested in (i.e. the sample at your fundamental frequency/harmonic)
EDIT: an example would be
t = [0 0 0 1 0 0 0];
f = fft(t);
phase = angle(f);
phase = angle(f(3)); % If you are interested in the phase of only one frequency
EDIT2: You should not mix up a real valued spectrum [which is basically abs(fft())] with a complex fourier transformed [which is only fft()]. But as you wrote that you calculated the fft yourself I guess you have the 'original' FFT with the complex numbers.

MATLAB program about sine and cosine functions

So I plot sine(w*time) vs cosine(w*time)
w being angular frequency.
Hope I'm not wasting anyone's time if I ask:
Would this look like a circle?
I've researched a whole bunch but most websites only graph sine and cosine side-by-side and show comparisons.
I got it to look like a circle and I was just wondering if this is correct.
Also, What can I call this plot? I just gave it a title "plot of a circle". But I am wondering if that is professional enough since I am doing it for class.
Thanks for your time and answers. Greatly appreciated.
My MATLAB code for anyone interested:
clear all; clc; % clear the Workspace and the Command Window
f = 2; w = 2*pi*f; % specify a frequency in Hz and convert to rad/sec
T = 0.01; % specify a time increment
time = 0 : T : 0.5; % specify a vector of time points
x = sin(w*time); % evaluate the sine function for each element of the vector time
y = cos(w*time);
plot(x,y)
axis equal
grid on
xlabel('sin(w*time)');ylabel('cos(w*time)');title('Plot of a Circle');
axis([-1.1 1.1 -1.1 1.1]);
print
Here is a link to a Wolfram Alpha query I just did:
http://www.wolframalpha.com/input/?i=x%3Dsin%28t%29%2C+y%3Dcos%28t%29
I am not sure if it what you want to see, but that site (WolframAlpha.com) is a great place to explore and challenge mathematical concepts that are new to you.
Also, I would call it a plot of a circle since that is what the output looks like.
You are making a Lissajous curve. Keep in mind that a cosine is just a sine offset by pi/2 radians, and so plotting a sine against a cosine will indeed result in a circle. Changing the frequency and/or relative phase between x(t) and y(t) will result in many different interesting patterns.

the Length of signal in calculating FFT

I want to ask some questions related to the last question of mine so I don't want to post in another thread. My question contains a code, I therefore can't post it as a comment. So I have to edit my old question into a new one. Please take a look and help. Thank you.
I'm new to FFT and DSP and I want to ask you some questions about calculating FFT in Matlab. The following code is from Matlab help, I just removed the noise.
Can I choose the length of signal L different from NFFT?
I'm not sure if I used window correctly. But when I use window (hanning in the following code), I can't get the exact values of amplitudes?
When L and NFFT get different values, then the values of amplitudes were different too. How can I get the exact value of amplitude of input signal? (in the following code, I used a already known signal to check if the code work correctly. But in case, I got the signal from a sensor and I dont know ahead its amplitude, how can I check?)
I thank you very much and look forward to hearing from you :)
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 512; % Length of signal
NFFT=1024; % number of fft points
t = (0:L-1)*T; % Time vector
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t); input signal
X = fft(hann(L).*x', NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
plot(f,2*abs(X(1:NFFT/2+1))) % Plot single-sided amplitude spectrum.
L is the number of samples in your input signal. If L < NFFT then the difference is zero-padded.
I would recommend you do some reading on the effect of zero-padding on FFTs. Typically it is best to use L = NFFT as this will give you the best representation of your data.
An excepted answer on the use of zero-padding and FFTs is given here:
https://dsp.stackexchange.com/questions/741/why-should-i-zero-pad-a-signal-before-taking-the-fourier-transform
In your experiment you are seeing different amplitudes because you will have different amount of spectral leakage with each different L.
You need to apply a window function prior to the FFT to get consistent results with frequency components that have non-integral number of periods within your sampling window.
You might also want to consider using periodogram instead of using the FFT directly - it takes care of window functions and a lot of the other housekeeping for you.

Confusion Regarding The Fourier Series In Matlab

I am currently studying DSP and i'm using the Matlab software package to work my way through the the problems. I am currently just starting to attempt to learn about the fourier series and am having trouble with the following problem.
Generate an 100hz triangle wave using Fourier Series.
Now, i cant quite understand this part of the problem about using the fourier series.
I have generated a 100hz triangle wave with the following matlab code:
t = 0:1/10000:1;
f=100;
x1 = sawtooth(2*pi*f*t, 0.5);
x2 = fft(x1);
plot(t,x1);
axis([0 0.10 -1 1]);
grid on;
Now what code would i use within matlab to plot the fourier series of this triangle wave?
Thanks to anyone who may have some input for this particular problem.
I think what the question is asking is for you to figure out the 'a' and 'b' coefficients and then generate the sawtooth wave by summing sines and cosines at the appropriate frequencies. It's not too hard to find the Fourier coefficients for a sawtooth wave online, but I encourage you to work it out and use that to check your answer :)
Then do something like this
n_harmonics = 10;
n = zeros(1, n_harmonics);
a = ?; % for you to figure out - probably a function of n
b = ?; % same idea
t = linspace(0, 2*pi);
x = zeros(size(t));
for nx = 1 : n,
x = x + a(nx)*cos(nx*t) + b(nx)*sin(nx*t);
end
plot(t, x)
Note the Fourier series is not the same thing as the Fourier transform, which is what fft is estimating. Most texts on signal processing will start with the Fourier series and build on that to get to the Fourier transform. Note also that there are tons of important and subtle differences when moving from continuous time to discrete time. Again, most textbooks will probably start with continuous time and then use that as a basis to introduce the discrete-time concepts.