Julia, run function multiple times, save results in array

风流意气都作罢 提交于 2019-12-05 11:02:33
Michael Ohlrogge

You are looking for the functions map and pmap (for parallelization). I've simplified your function to give a more minimal working example. (in the future, please see this link for guidance on creating such minimal examples in your questions).

map takes a function (that you specify) and applies it to all of the elements in an array. If your function takes multiple arguments (as yours does), then you simply feed map multiple successive arrays. map then returns a new array with the results of all your functions.

function MicroSim(start_age, stages)
    return rand(start_age), rand(stages)
end

Start_Ages = [10, 20, 15]
Stages = [1, 4, 5]

Results = map(MicroSim, Start_Ages, Stages)

If you want to parallelize things, there are just three simple adjustments. 1. use the addprocs() function to add however many additional processes you want. 2. use the @everywhere macro when declaring your function so that your worker processes also have access to it. 3. use the function pmap instead of map:

addprocs(2)

@everywhere begin
    function MicroSim(start_age, stages)
        return rand(start_age), rand(stages)
    end
end

Results = pmap(MicroSim, Start_Ages, Stages)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!