Hi!

I have a function simulation( p ) which returns a 2D (n by T) array of states, the state for each simulated time step. ‘p’ just stands for some parameters.

I also have to run a multitude of N simulations and I want to do it efficiently. So, I want to use a function simulation(p, N) which returns a 3D (n by T by N) array of the states. My question is, what is the most efficient way to reuse the code I already have in simulation§?

**Basic solution:**

```
function solution(p, N)
x = Array{Float64,3}(n,T,N)
for i = 1:N
x[1:n,1:T,i] = simulation(p)
end
return x
end
```

My issue here is that as far as I know, there is a lot of overhead due to simulation§ allocating each x_i generated trajectory, which is then copied into x[1:n,1:T,i].

**Preferred solution:**

I would instead use a solution!(p, x) function which modifies the preallocated x array where the result would be stored. Then I would hope for something along the lines of:

```
function solution(p, N)
x = Array{Float64,3}(n,T,N)
for i = 1:N
simulation!(p, x[1:n,1:T,i])
end
return x
end
```

However, as far as I understand, putting in x[1:n,1:T,i] as the argument to simulation! actually copies that part of the array, so x itself will not be overwritten and in this form this does not work.

**Unpreferred but working solution:**

I can create the function solution!(p, x, i), which accepts a 3 dimensional array and modifies only the part where the last component has index i. Then I can use:

```
function solution(p, N)
x = Array{Float64,3}(n,T,N)
for i = 1:N
simulation!(p, x, i)
end
return x
end
```

which should do the trick. My problem with this solution, is that I also just want to be able to use the simulation!(p, x) function without a 2D array, and I do not know how to have simulation!(p, x) and simulation!(p, x, i) boil down to the same code, due to the different way x has to be accessed and treated in them. This is what I could avoid by the preferred solution, where I still only have the simulation!(p, x) function operating on a 2D array, without supplying any additional index i.

Any help or suggestion on how this is usually done is appreciated!

Best,

Tusike