Amplitude and Phase of FFT - r

I have a sound function I am trying to break up into sines/cosines. So I resorted to Fast Fourier Transformation. By using the fft(y,inverse=FALSE) function I was able to convert the time domain of the sound into the frequency doman. The output is complex. I read that in order to convert this output which is in imaginary form and weed out the necessary information, which are the amplitude and the phase of A(v)cos(2*pi*v+P), one must use the abs() of the output to get the amplitude; however I am having difficulty finding the R function that gets us the phase. In MATLAB, the angle() function returns the phases of the FFT. What is the respective function in R to find the phase??
Update
Thank you for the suggestions guys; still expericieng an issue. I am running FFT on a simple function to test to see if it works. My function is y=cos(2*pi*(seq(0,10,by=.01)*(1/5)+7.5).
So the frequency is 1/5 with a phase shift of 7.5.
y=cos(2*pi*(seq(0,10,by=.01)*(1/5)+7.5)
fty=(y,inverse=F)
plot(abs(fty),xlim=c(0,10),type="l")
angle=atan2(Im(fty), Re(fty))
> angle[3]
[1] 1.222766
When I plot the series, the amplitude is peaking at a frequency value of 3 and the angle function (which should give me my phase at the frequency at which amplitude peaks at) is giving me a phase of 1.2. What am I doing wrong?

You might find that the atan2 function does what you want. You would give it the imaginary and real parts of the value, since the prototype is atan2(y, x). So you could do:
angle = atan2(Im(value), Re(value));

Related

Double discrete integration of periodic function with R: doubly integrated function contains linear artifact

I need to integrate a signal from accelerometer, in order to get speed and position over time.
I'm trying the code on some code-generated acceleration data:
1)squarewave
2)sawtooth
3)sin
The speed function obtained is ok, the problem is with the position function obtained integrating speed. IN each case (squarewave, sawtooth, sin) the doubly discrete-integrated funtion shows a linear term superposed to the expected oscillating one.
I've perfomed this discrete-integration with both diffinv() function and with this custom function I've written:
#function that, given a function sampled at some time values, calculates its primitive
calculatePrimitive<-function(f_t, time, initialValue){
F_t<-0
F_t[1]<-initialValue
for (i in 2:length(f_t)) {
F_t[i] <- F_t[i-1] + (( (f_t[i]+f_t[i-1])/2 )*(time[i]-time[i-1]) )
}
F_t
}
The result is the same, no matter which function i use to performe the discrete integration, and it is shown in the attached graphs for cases 1) to 3).
I don't understand why this happen when, no matter what is the acceleration data, the discrete integration is applied to data that have been obtained by descrete integration themselves.

Why are frequencies represented as complex numbers?

In a FFT, the resulting frequencies represent both magnitude and phase. Since each frequency element in the output array of an FFT essentially just describes the SIN wave at each frequency interval, shouldn't it just be magnitude that we need? What is the significance of the phase represented in the imaginary part of the complex number?
To clarify my question, to be able to put a meaning to the phase of a wave, I need a reference point or reference wave.
When an FFT reports the phase for each sin wave in the resulting frequency domain output, what is the reference wave with respect to which it is reporting the phase?
Because the phase of different components affects the total signal. The two functions in the plot are both summed from sine waves with periods of pi and 2pi, but the phase of the p=2pi sine waves are different. As you can see, the outputs are not the same.
Well in layman's words: magnitude tells you how much of that frequency is there, and phase tells you where it is.
FFTs (there is more than one convention) usually report phase with respect to the zero-th sample. Or if you use FFTShift, with respect to the sample at the center of an FFT window that indexes from 0 to N-1 (e.g. sample number N/2 = sin(0) for a phase of 0). The latter convention, centering phase using FFTShift, is often better, as there can be a big discontinuity at the edges of an FFT aperture, or nearly no data at the edges after using a tapered window function.
If you use FFTShift to center the phase reference, zero phase represents an even function, and a phase of pi or -pi represents an odd function in the window.
Human hearing, in general, can't discriminate the phase of a single sound source. BUT, phase is important when dealing with combined sounds, or multiple sine waves of the same frequency. Sinusoids that are in phase add or sum. Sinusoids of the opposite phase cancel. So if you have the FFT of, say, two loudspeaker responses without phase, you won't know whether they will sound great or horrible together.

Converting Real and Imaginary FFT output to Frequency and Amplitude

I'm designing a real time Audio Analyser to be embedded on a FPGA chip. The finished system will read in a live audio stream and output frequency and amplitude pairs for the X most prevalent frequencies.
I've managed to implement the FFT so far, but it's current output is just the real and imaginary parts for each window, and what I want to know is, how do I convert this into the frequency and amplitude pairs?
I've been doing some reading on the FFT, and I see how they can be turned into a magnitude and phase relationship but I need a format that someone without a knowledge of complex mathematics could read!
Thanks
Thanks for these quick responses!
The output from the FFT I'm getting at the moment is a continuous stream of real and imaginary pairs. I'm not sure whether to break these up into packets of the same size as my input packets (64 values), and treat them as an array, or deal with them individually.
The sample rate, I have no problem with. As I configured the FFT myself, I know that it's running off the global clock of 50MHz. As for the Array Index (if the output is an array of course...), I have no idea.
If we say that the output is a series of One-Dimensional arrays of 64 complex values:
1) How do I find the array index [i]?
2) Will each array return a single frequency part, or a number of them?
Thankyou so much for all your help! I'd be lost without it.
Well, the bad news is, there's no way around needing to understand complex numbers. The good news is, just because they're called complex numbers doesn't mean they're, y'know, complicated. So first, check out the wikipedia page, and for an audio application I'd say, read down to about section 3.2, maybe skipping the section on square roots: http://en.wikipedia.org/wiki/Complex_number
What that's telling you is that if you have a complex number, a + bi, you can picture it as living in the x,y plane at location (a,b). To get the magnitude and phase, all you have to do is find two quantities:
The distance from the origin of the plane, which is the magnitude, and
The angle from the x-axis, which is the phase.
The magnitude is simple enough: sqrt(a^2 + b^2).
The phase is equally simple: atan2(b,a).
The FFT result will give you an array of complex values. The twice the magnitude (square root of sum of the complex components squared) of each array element is an amplitude. Or do a log magnitude if you want a dB scale. The array index will give you the center of the frequency bin with that amplitude. You need to know the sample rate and length to get the frequency of each array element or bin.
f[i] = i * sampleRate / fftLength
for the first half of the array (the other half is just duplicate information in the form of complex conjugates for real audio input).
The frequency of each FFT result bin may be different from any actual spectral frequencies present in the audio signal, due to windowing or so-called spectral leakage. Look up frequency estimation methods for the details.

Function for returning a list of points on a Bezier curve at equal arclength

Someone somewhere has had to solve this problem. I can find many a great website explaining this problem and how to solve it. While I'm sure they are well written and make sense to math whizzes, that isn't me. And while I might understand in a vague sort of way, I do not understand how to turn that math into a function that I can use.
So I beg of you, if you have a function that can do this, in any language, (sure even fortran or heck 6502 assembler) - please help me out.
prefer an analytical to iterative solution
EDIT: Meant to specify that its a cubic bezier I'm trying to work with.
What you're asking for is the inverse of the arc length function. So, given a curve B, you want a function Linv(len) that returns a t between 0 and 1 such that the arc length of the curve between 0 and t is len.
If you had this function your problem is really easy to solve. Let B(0) be the first point. To find the next point, you'd simply compute B(Linv(w)) where w is the "equal arclength" that you refer to. To get the next point, just evaluate B(Linv(2*w)) and so on, until Linv(n*w) becomes greater than 1.
I've had to deal with this problem recently. I've come up with, or come across a few solutions, none of which are satisfactory to me (but maybe they will be for you).
Now, this is a bit complicated, so let me just give you the link to the source code first:
http://icedtea.classpath.org/~dlila/webrevs/perfWebrev/webrev/raw_files/new/src/share/classes/sun/java2d/pisces/Dasher.java. What you want is in the LengthIterator class. You shouldn't have to look at any other parts of the file. There are a bunch of methods that are defined in another file. To get to them just cut out everything from /raw_files/ to the end of the URL. This is how you use it. Initialize the object on a curve. Then to get the parameter of a point with arc length L from the beginning of the curve just call next(L) (to get the actual point just evaluate your curve at this parameter, using deCasteljau's algorithm, or zneak's suggestion). Every subsequent call of next(x) moves you a distance of x along the curve compared to your last position. next returns a negative number when you run out of curve.
Explanation of code: so, I needed a t value such that B(0) to B(t) would have length LEN (where LEN is known). I simply flattened the curve. So, just subdivide the curve recursively until each curve is close enough to a line (you can test for this by comparing the length of the control polygon to the length of the line joining the end points). You can compute the length of this sub-curve as (controlPolyLength + endPointsSegmentLen)/2. Add all these lengths to an accumulator, and stop the recursion when the accumulator value is >= LEN. Now, call the last subcurve C and let [t0, t1] be its domain. You know that the t you want is t0 <= t < t1, and you know the length from B(0) to B(t0) - call this value L0t0. So, now you need to find a t such that C(0) to C(t) has length LEN-L0t0. This is exactly the problem we started with, but on a smaller scale. We could use recursion, but that would be horribly slow, so instead we just use the fact that C is a very flat curve. We pretend C is a line, and compute the point at t using P=C(0)+((LEN-L0t0)/length(C))*(C(1)-C(0)). This point doesn't actually lie on the curve because it is on the line C(0)->C(1), but it's very close to the point we want. So, we just solve Bx(t)=Px and By(t)=Py. This is just finding cubic roots, which has a closed source solution, but I just used Newton's method. Now we have the t we want, and we can just compute C(t), which is the actual point.
I should mention that a few months ago I skimmed through a paper that had another solution to this that found an approximation to the natural parameterization of the curve. The author has posted a link to it here: Equidistant points across Bezier curves

FFT in MATLAB ( I need help)

Could anybody please tell me whether I can perform this integration with FFT in MATLAB? How?
Please answer as soon as possible with the details.
Suppose there exists 2 rectangular planes, say, input accessed by x1 and y1 variables and the resulting plane is output accessed by tetax and tetay variables.
This is the integral in pseudo-code:
output(tetax,tetay)=double integral of [input(x1,y1)*exp(-j*k*((tetax*x1)+(tetay*y1)))](dx1)(dy1)
where: -1<= x1 <= 1 and -1<= y1 <= 1
tetax and tetay should change so they can span the final rectangular plane.
I would really appreciate a prompt and detailed answer.
Since this looks like homework, I'll just give some hints. The trick is to rewrite the integral to look like a normal 2D Fourier integral of a function.
There are two issues:
1) You need to combine k and your tetax, tetay to look like a normal wavenumber (and compensate for this in the appropriate way).
2) You need to deal with the limits being in the range (-1,1) whereas the Fourier integral needs them in the range (-inf, +inf). To do this, pick a function to go inside the Fourier integral that will make this work.
Then it will be obvious how to do this in Matlab. It's a cute problem and I hope this doesn't ruin it (and if people think it does, let me know and I'll delete this answer, or delete it for me if you can).
Your problem looks like a Fourier transform, not a discrete Fourier transform (DFT). A FFT calculates the latter type of transform.
Briefly, a Fourier transform involves an integral, while a DFT involves a sum.

Resources