Hilbert Transform in C provides possibly strange results I am calculating some signals that depend on the Hilbert Transform and, after following various guides online and SO, my function looks like this:

void Hilbert_Transf(COMPLEX *cplx_data, const int LENGTH)
    {
    float Imag_Val = 0.0f;
    for(int i = 0; i &lt; LENGTH; i++)
        {
        Imag_Val = cplx_data[i].y;
        cplx_data[i].y = (Imag_Val &gt; 0 ? -PI / 2 : (Imag_Val &lt; 0 ? PI / 2 : 0));
        }
    }


It is essentially testing if the imaginary value is positive, so it is replaced by -PI / 2, or by PI / 2 if it is negative, and by 0 if 0.
To test the function I used a sine wave, computed by:

const int LENGTH = 1024;
float input[LENGTH];
for(int i = 0; i &lt; LENGTH; i++)
    input[i] = sin(i * 2 * PI * 0.01);


The FFT process  is throught Intel MKL, so in the function above I just considered COMPLEX *cplx_data to be a complex in the form MKL takes and the member .y being its imaginary part.
Then I write to files the input data (sine wave) and output from the HT, and plot them.



So you can see the input sine in blue and the HT of it in red, as well as the "serrated" peaks, troughs. I wasn't expecting this "stepped" behavior. Can you guys tell me what is wrong/missing and how it should be? If you need more information, just let me know.

========== EDIT ===========

Matt L., following your script, here is the result of a plot which looks more decent:



Blue is the input and red, the output. I will of course find a way to reproduce this in C, but I will ask a couple more questions on the comments so we can close it.
The function in your question doesn't compute the Hilbert transform.

The Hilbert transform can be implemented either in the time domain by filtering the input signal with a filter kernel that approximates the ideal kernel of the Hilbert transform (there are approximations for FIR and IIR Hilbert transformers), or it can be implemented in the frequency domain.

An example of a frequency domain implementation is the Matlab/Octave function hilbert. But note that this function actually computes the analytic signal, so the Hilbert transform is the imaginary part of the result.

A simple direct frequency domain implementation of the Hilbert transform is shown in the Matlab/Octave script below. Note that it only uses real (I)FFTs.


% compute Hilbert transform of vector x

N = length(x);
X = fft(x);

if ~rem(N,2),       % N is even

    n = N/2;

    % set values at DC and Nyquist to zero
    X(1) = 0; X(n+1) = 0;

    % multiply with -1i * sign(w)
    X(2:n) = -1i * X(2:n);
    X(n+2:N) = 1i * X(n+2:N);

else                % N is odd

    n = (N+1)/2;

    % set value at DC to zero
    X(1) = 0;

    % multiply with -1i * sign(w)
    X(2:n) = -1i * X(2:n);
    X(n+1:N) = 1i * X(n+1:N);

endif

y = real(ifft(X));