Julia Community 🟣

Matthew leung
Matthew leung

Posted on

Playing with Broadcast function

One of the features in Julia is the broadcast function. It is very easy to apply the function to each element in the array with the broadcast operator ".".

However, if the function needs to take some other arguments which is not for iteration, how to do that?

Let's take an example. How to use broadcast function to calculate the moving average?

The for-loop version of the moving average is:

function ma_loop(vec,win_size)
    n = size(vec)[1]
    ma = Array{Float64}(undef, n)
    for i in 1:n
        if i >= win_size
            ma[i] = sum(vec[i-win_size+1:i])/win_size
        end
    end
    return ma[win_size:end]
end
Enter fullscreen mode Exit fullscreen mode

To use broadcast function to replace the for-loop, I try to iterate the index array (1:n), and passing the Reference of the whole vector (Ref(vec)) and the window size (win_size) as the function arguments. As these 2 arguments are not in the form of array or list, the broadcast function will not iterate on them, but just pass them in each iteration.

function moving_avg(vec,win_size)
    n = size(vec)[1]
    return window_avg.(Ref(vec),win_size,1:n)[win_size:end]
end
function window_avg(a,win,i)
    if i>=win
        return sum(a[i-win+1:i])/win
    end
end
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)