# Faster way to Implement a CFAR (window average) Threshold

I implemented a version of a CFAR average in MATLAB but it's 'slow' and I need to speed it up. I included the pseudo code and logic below. I used a nested for loop to calculate the moving average but this is no good since I want to run this on hundreds of millions of sample points. Does anyone have any methods for making this run faster? As long as it doesn't use a nested for loop, anything is better. Any suggestions for using just one for loop?

This is the picture I used to calculate the lead and lag training windows. I am looping though all the points in my range window and calculating average lead and lag on the training samples for the cell under test CUT. For the CUT near the start or end of the range window, I used either the lead or lag and used double the training size. Again this is pseudo code so I don't care about saving off my values. Overwriting values is fine for now. Data is my MATLAB variable I am using to calculate the CFAR average.

Please let me know how to speed this up!

https://www.mathworks.com/help/phased/ug/fpga-based-cell-averaging-cfa.html

[![enter image description here][1]][1] [![enter image description here][2]][2]

range_window_length=1000;
G=2;
T=50;

For n=1:range_window_length
% Condition if CUT is less than G+T
if n<G+T
lag_cum=0
for i=n+G:n+G+T*2 %use 2 times T
lag_cum=lag_cum+data(i)
end
% Condition if CUT is greater than than range window length minus (G+T)
elseif n>range_window_length-(G+T)
for i=n-G-2*T : n-G
end
% middle region calculate lead and lag
else
for i=n-G-T:n-G
end
lag_cum=0;
for i=n+G:n+G+T
lag_cum=lag_cum+data(i);
end
end
end

[1]: https://i.stack.imgur.com/EQAJn.png
[2]: https://i.stack.imgur.com/7cL72.png

• Can you use filter(), conv() or movsum() functions? They are implemented as library functions using whatever low level programming is needed to make them fast. Aug 11, 2021 at 22:34

• Numpy is based on BLAS and LAPACK. MATLAB uses the fastest libraries for those on x86 world (Intel MKL). Numpy also use them (The Anaconda distribution). So per command there is no advantage for any. On non vectorized code MATLAB can use JIT engine while, at the moment, the CPython doesn't have.