# Improving for loop speed in recursive calculation

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

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?

2 Likes