Search code examples
functionjuliabroadcast

Collect values from function in Julia


My question is regarding the use of the broadcast operator in Julia.

Suppose I have the following objects

M = [0.7 0.3; 0.4 0.6];
x0 = [100 100];
N=5;
y = zeros(N, size(x0)[2]);

function Markov_bling_bling(;Trans_mat, initial_states, n_ahead)
    # Define useful names
    M = Trans_mat; x0 = initial_states; N = n_ahead;
    # Compute the N-th state 
    xn = x0 * M^N
    return(x_n = xn)
end

(Sorry for the silly name)

So this function returns a 1x2 vector.

So I would like to store every xn as a row in y.

In R I would do this:

y <- list()
for(t in 1:(N+1)){
  y[t] = Markov_bling_bling(Trans_mat = M, initial_states = x0, n_ahead=(t-1))
}

y <- Reduce(rbind,x)

How can I accomplish this in Julia? I know that I have to use the broadcast operator in order to avoid a for loop.

But I still don't get how can I store the results, should I define y = []? What is Julia way to store results?

Thanks in advance!


Solution

  • It can be written in almost the same way as in R:

    julia> reduce(vcat, [Markov_bling_bling(Trans_mat = M, initial_states = x0, n_ahead=(t-1)) for t in 1:N])
    5×2 Matrix{Float64}:
     100.0   100.0
     110.0    90.0
     113.0    87.0
     113.9    86.1
     114.17   85.83