%% Create a Vector-Input IFFT for HDL Code Generation
%%  
% Create the specifications and input signal. This example uses a
% 128-point FFT and computes the transform over 16 samples at a time.  
N = 128; 
V = 16;
Fs = 40; 
t = (0:N-1)'/Fs;
x = sin(2*pi*15*t) + 0.75*cos(2*pi*10*t);
y = x + .25*randn(size(x));
y_fixed = sfi(y,32,24);
y_vect = reshape(y_fixed,V,N/V);
%% 
% Compute the FFT of the signal, to use as the input to the IFFT object. 
% 
% *Note:* This object syntax runs only in R2016b or later. If you are using an 
% earlier release, replace each call of an object with the equivalent |step|
% syntax. For example, replace |myObject(x)| with |step(myObject,x)|.
hdlfft = dsp.HDLFFT('FFTLength',N);
loopCount = getLatency(hdlfft,N,V)+N/V;
Yf = zeros(V,loopCount);
validOut = false(V,loopCount);
for loop = 1:1:loopCount 
    if ( mod(loop,N/V) == 0 ) 
        i = N/V; 
    else
        i = mod(loop,N/V); 
    end
 	  [Yf(:,loop),validOut(loop)] = hdlfft(complex(y_vect(:,i)),(loop<=N/V)); 
end
%% 
% Plot the single-sided amplitude spectrum.
C = Yf(:,validOut==1);
Yf_flat = C(:);
Yr = bitrevorder(Yf_flat);
plot(Fs/2*linspace(0,1,N/2),2*abs(Yr(1:N/2)/N))
title('Single-Sided Amplitude Spectrum of Noisy Signal y(t)')
xlabel('Frequency (Hz)')
ylabel('Output of FFT(f)')
%% 
% Select frequencies that hold the majority of the energy in the signal.
% The |cumsum| function doesn't accept fixed-point arguments, so convert
% the data back to |double|.
[Ysort,i] = sort(abs(double(Yr(1:N))),1,'descend');
CumEnergy = sqrt(cumsum(Ysort.^2))/norm(Ysort);
j = find(CumEnergy > 0.9, 1);
     disp(['Number of FFT coefficients that represent 90% of the ', ...
     'total energy in the sequence: ', num2str(j)])  
Yin = zeros(N,1);
Yin(i(1:j)) = Yr(i(1:j));
YinVect = reshape(Yin,V,N/V);
%%  
% Write a function that creates and calls the IFFT System object(TM). You 
% can generate HDL from this function. 
%
% <include>HDLIFFT128V16.m</include> 
%
%%
% Compute the IFFT by calling the function for each data sample.
Xt = zeros(V,loopCount);
validOut = false(V,loopCount);
for loop = 1:1:loopCount 
    if ( mod(loop,N/V) == 0 ) 
        i = N/V; 
    else
        i = mod(loop,N/V); 
    end
 	  [Xt(:,loop),validOut(loop)] = HDLIFFT128V16(complex(YinVect(:,i)),(loop<=N/V)); 
end
%% 
% Discard invalid output samples. Then inspect the output and compare it
% with the input signal. The original input is in green.
C = Xt(:,validOut==1);
Xt = C(:);
Xt = bitrevorder(Xt);
norm(x-Xt(1:N))
figure
stem(real(Xt))
figure
stem(real(x),'--g')

%% 
% Copyright 2012 The MathWorks, Inc.