Trying to plot the fft of a sinc function - matlab

I am trying to plot the fft of a set of data I have. These data form a nearly perfect sinc function. Here is the data of which I am trying to plot the fft:
.
I know the fft of a sinc function should look like kind of a step function. However, the results I get are nowhere near that. Finding the fft in itself is super easy, but I think my mistake is when I try to compute the frequency axis. I have found several methods online, but so far I have not been able to make it work. Here is my code:
sampleRate = (max(xdata) - min(xdata))/length(xdata);
sampleN = length(xdata);
y = fft(ydata, sampleN);
Y = y.*conj(y)/sampleN;
freq = (0:1:length(Y)-1)*sampleRate/sampleNumber;
plot(freq, Y)
I have found pretty much all of that online and I understand pretty much none of it (which might be why it's not working...)
Zoom on what I get using that code:
It now seems to be working! This is what I get when I subtract the mean:

What you see here is the zero frequency being much, much larger than everything else. Plot with plot(freq,Y,'o-') to prove that the shape you see is just the linear interpolation between two samples.
The zero frequency is the sum of all samples. Because the mean of your signal is quite a bit larger than the amplitude, the zero frequency dwarfs everything else. And because you are plotting the power (absolute square of the DFT), this difference is enhanced even more.
There are two simple solutions:
Plot using logarithmic y-axis:
plot(freq, Y)
set(gca,'yscale','log')
Subtract the mean from your signal, remove the zero frequency, or scale the y-axis (these are all more or less equivalent):
y = fft(ydata-mean(ydata), sampleN);
or
y(1) = 0;
or
plot(freq, Y)
set(gca,'ylim',[0,max(Y(2:end))]);

Related

Find zero crossing points in a signal and plot them matlab

I have a signal 's' of voice of which you can see an extract here:
I would like to plot the zero crossing points in the same graph. I have tried with the following code:
zci = #(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Zero-Crossing Indices Of Argument Vector
zx = zci(s);
figure
set(gcf,'color','w')
plot(t,s)
hold on
plot(t(zx),s(zx),'o')
But it does not interpole the points in which the sign change, so the result is:
However, I'd like that the highlighted points were as near as possible to zero.
I hope someone can help me. Thanks you for your responses in advanced.
Try this?
w = 1;
crossPts=[];
for k=1:(length(s)-1)
if (s(k)*s(k+1)<0)
crossPts(w) = (t(k)+t(k+1))/2;
w = w + 1;
end
end
figure
set(gcf,'color','w')
plot(t,s)
hold on
plot(t, s)
plot(crossPts, zeros(length(crossPts)), 'o')
Important questions: what is the highest frequency conponent of the signal you are measuring? Can you remeasure this signal? What is your sampling rate? What is this analysis for? (Schoolwork or scholarly research). You may have quite a bit of trouble measuring the zeros of this function with any significance or accurracy because it looks like your waveform has a frequency greater than half of your sampling rate (greater than your Nyquist frequency). Upsampling/interpolating your entire waveform will allow you to find the zeros much more precisely (but with no greater degree of accurracy) but this is a huge no-no in the scientific community. While my method may not look super pretty, it's the most accurate method that doesn't make unsafe assumptions. If you just want it to look pretty, I would recommend interp1 and using the 'Spline' method. You can interpolate the whole waveform and then use the above answer to find more accurate zeros.
Also, you could calculate the zeros on the interpolated waveform and then display it on the raw data.
A remotely possible solution to improve your data;
If you're measuring a human voice, why not try filtering at the range of human speech? This should be fine mathematically and could possibly improve your waveform.

MATLAB sine wave plot is not correct

I am new to MATLAB and I wrote some code to generate a sine wave. However the graph is not correct. Here is the screenshot of my code and the plot
What is the problem? Please help!
MATLAB plots discrete points and simply draws a straight line to connect neighbouring points together. Your time points are one second (1s) in between, and you are specifying a frequency of 100 Hz. In addition, because your sampling time is a multiple of the period of your sine wave, substituting all of those values of t would thus make the sin result equal to 0, though there is some numerical imprecision. Specifically, if you look at the y-axis, you'll see that the magnitude of your numbers is around 10^{-13}. However even if you escape this, the sampling time is TOO LARGE for the specified frequency of your wave and so this huge gap in between points is visualized as that jagged wave that you see in your graph.
The solution is to simply make your sampling time smaller. Try something small, like 1e-4 for example:
t = 0:1e-4:0.05;
f = 100;
A = 2;
x = A*sin(2*pi*f*t);
plot(t,x);
We get this now:

matlab: cdfplot of relative error

The figure shown above is the plot of cumulative distribution function (cdf) plot for relative error (attached together the code used to generate the plot). The relative error is defined as abs(measured-predicted)/(measured). May I know the possible error/interpretation as the plot is supposed to be a smooth curve.
X = load('measured.txt');
Xhat = load('predicted.txt');
idx = find(X>0);
x = X(idx);
xhat = Xhat(idx);
relativeError = abs(x-xhat)./(x);
cdfplot(relativeError);
The input data file is a 4x4 matrix with zeros on the diagonal and some unmeasured entries (represent with 0). Appreciate for your kind help. Thanks!
The plot should be a discontinuous one because you are using discrete data. You are not plotting an analytic function which has an explicit (or implicit) function that maps, say, x to y. Instead, all you have is at most 16 points that relates x and y.
The CDF only "grows" when new samples are counted; otherwise its value remains steady, just because there isn't any satisfying sample that could increase the "frequency".
You can check the example in Mathworks' `cdfplot1 documentation to understand the concept of "empirical cdf". Again, only when you observe a sample can you increase the cdf.
If you really want to "get" a smooth curve, either 1) add more points so that the discontinuous line looks smoother, or 2) find any statistical model of whatever you are working on, and plot the analytic function instead.

How to produce a log scale FFT with MatLab

It's my first time performing an FFT within MatLab by experimenting with some example code from the MathWorks website. I was wondering if it was possible to take the code I have and transform the x axis to a log-scale representation rather than linear. I understand most of the code, but it is the x axis line of code that I'm still not 100% sure exactly what it is doing apart from the +1 at the end of the line, which is that fact that MatLab's indexing structure doesn't start on 0.
My code so far is:
[y,fs] = wavread('Wav/800Hz_2sec.wav');
NFFT = 4096;
Y = fft(y,NFFT)/length(y);
f = fs/2*linspace(0,1,NFFT/2+1);
plot(f,2*abs(Y(1:NFFT/2+1))
frequency usually comes out in linear scale from Discrete Fourier Transform. if you want, you can make a new frequency vector in log scale and interpolate the results you already have
fnew=fs/2.*logspace(log10(fs/length(y)),0,npts);
Ynew= interp1(f,Y(1:NFFT/2+1),fnew);
where npts is the length of your new frequency vector. for just plotting
loglog(f,2*abs(Y(1:NFFT/2+1));
honestly IMO, the interpolation thing doesn't work very well because FFT of real signals produces strong peaks and troughs in spectra, so unless you smooth your spectrum first, the interpolated spectrum won't look as nice

Plotting the log amplitude and frequency

I'm trying to display a spectrum of a sound sample with the correct frequency-axis, in Hertz, and a
log-amplitude y-axis. I thought I had the frequency display right, but the graphs that it produces look rather weird and I've found absolutely nothing regarding displaying the log amplitude on an axis.
The code that I'm using (heavily borrowed from mathsworks fft example) is:
y=x(100:200);
Fs = 10000; % Sampling frequency
numsamples = 20000; % Number of samples in the signal
NFFT = 2^nextpow2(numsamples); % Next power of 2 from length of y
Y = fft(y,NFFT)/numsamples;
f = Fs/2*linspace(0,1,NFFT/2+1);
plot(f,2*abs(Y(1:NFFT/2+1)))
And here's one of the graphs that it produced:
I don't know if that's right or not, but it doesn't look anything like the examples I've seen....
I'm aware this is probably a really stupid question and I'm missing something obvious, or maybe I've actually got it right and don't understand enough to realise it, but this stuff is really doing my head in and I'm not finding the documentation particularly illuminating.
I think the x-axis is correct.
To obtain a logarithmic y-axis replace the plot bysemilogy:
semilogy(f,2*abs(Y(1:NFFT/2+1)))
or equivalently use plot as it stands followed by
set(gca,'YScale','log')