# Improving for loop speed in recursive calculation

**URL:** <https://discourse.julialang.org/t/improving-for-loop-speed-in-recursive-calculation/95848>\
**Category:** Performance\
**Created:** [March 10, 2023, 8:46am UTC](https://discourse.julialang.org/t/improving-for-loop-speed-in-recursive-calculation/95848 "2023-03-10T08:46:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![marianoarnaiz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marianoarnaiz/32/19377_2.png) [@marianoarnaiz](https://discourse.julialang.org/u/marianoarnaiz)\
**Post date:** [March 10, 2023, 8:46am UTC](https://discourse.julialang.org/t/improving-for-loop-speed-in-recursive-calculation/95848/1 "2023-03-10T08:46:10Z")

</div>

Hi all.  
I am building a little function that does some recursive computation. it will be working in very large datasets and I want to speed it up.

Maybe someone can give a helping hand? 🙂

> function rec\_hos(signal; C::Float64, order::Int64, var\_min=-1, definition=0)
> 
> ss=size(signal,1) #signal size  
> mean = zeros(ss)  
> var = ones(ss)  
> hos = zeros(ss)  
> n\_win=Int64(round(1/C))
> 
> for i=1:n\_win
> 
> ```
> mean[end] = C * signal[i] + (1 - C) * mean[end]
> var[end] = C * (signal[i] - mean[end])^2 + (1 - C) * var[end]
> 
> ```
> 
> if definition == 0
> 
> ```
> for j = 2:ss
> mean[j] = C * signal[j] + (1 - C) * mean[j-1]
> var[j] = C * (signal[j] - mean[j-1])^2 + (1 - C) * var[j-1]        
> if var[j] < var_min
> _var = var[j]# or 1e-9
> else
> _var = var_min
> end       
> hos[j] = C * ((signal[j] - mean[j-1])^order / _var^(order/2))
> hos[j] += (1 - C) * hos[j-1]
>     
> end
> 
> ```
> 
> elseif definition == 1
> 
> ```
> for j = 2:ss
> mean[j] = C * signal[j] + (1 - C) * mean[j-1]
> var[j] = C * (signal[j] - mean[j])^2 + (1 - C) * var[j-1]
> if var[j] < var_min
> _var = var[j]# or 1e-9
> else
> _var = var_min
> end
> hos[j] = C * ((signal[j] - mean[i])^order / _var^(order/2))
> hos[j] += (1 - C) * hos[j-1]
> end
> 
> ```
> 
> end  
> end
> 
> return hos./maximum(hos)  
> end

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [March 10, 2023, 12:15pm UTC](https://discourse.julialang.org/t/improving-for-loop-speed-in-recursive-calculation/95848/2 "2023-03-10T12:15:04Z")

</div>

Please quote your code with triple-back ticks: ``` (the \</\> button does that to you).

Also can you provide a runnable example? What’s recursive there?
