%% Compute Magnitude and Phase Angle of Complex Signal
% Use the |dsp.HDLComplextoMagnitudeAngle| object to compute the magnitude 
% and phase angle of a complex signal. The object uses a CORDIC
% algorithm for an efficient hardware implementation.  
%% 
% Choose word lengths and create random complex input signal. Then, convert
% the input signal to fixed-point. 
a = -4; 
b = 4;
inputWL = 16;
inputFL = 12;
numSamples = 10;
reData = ((b-a).*rand(numSamples,1)+a);
imData = ((b-a).*rand(numSamples,1)+a);
dataIn = (fi(reData+imData*1i,1,inputWL,inputFL));  
figure
plot(dataIn)
title('Random Complex Input Data')
xlabel('Real')
ylabel('Imaginary')
%% 
% Write a function that creates and calls the System object(TM). You
% can generate HDL from this function. 
% 
% *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)|.
%
% <include>Complex2MagAngle.m</include> 
%
%%
% The number of CORDIC iterations determines the latency that the object 
% takes to compute the answer for each input sample. The latency is 
% |NumIterations+4|. In this example, |NumIterationsSource| is set to the 
% default, |'Auto'|, so the object uses |inputWL-1| iterations. The latency
% is |inputWL+3|.  
latency = inputWL+3;
mag = zeros(1,numSamples+latency);
ang = zeros(1,numSamples+latency);
validOut = false(1,numSamples+latency);
%% 
% Call the function to convert each sample. After you apply all input
% samples, continue calling the function with invalid input to flush
% remaining output samples.
 
for ii = 1:1:numSamples
   [mag(ii),ang(ii),validOut] = Complex2MagAngle(dataIn(ii),true);             
end
for ii = (numSamples+1):1:(numSamples+latency)
   [mag(ii),ang(ii),validOut(ii)] = Complex2MagAngle(fi(0+0*1i,1,inputWL,inputFL),false);             
end
% Remove invalid output values
mag = mag(validOut == 1);
ang = ang(validOut == 1);
figure
polar(ang,mag,'--r')   % Red is output from HDL-optimized System object
title('Output from dsp.HDLComplexToMagnitudeAngle')
magD = abs(dataIn); 
angD = angle(dataIn);
figure
polar(angD,magD,'--b') % Blue is output from abs and angle functions
title('Output from abs and angle Functions')