# Replace for loop with vectorized call of a function that returns multiple values

**URL:** https://discourse.julialang.org/t/replace-for-loop-with-vectorized-call-of-a-function-that-returns-multiple-values/52476
**Category:** General Usage
**Tags:** vector
**Created:** [December 27, 2020, 8:30pm UTC](https://discourse.julialang.org/t/replace-for-loop-with-vectorized-call-of-a-function-that-returns-multiple-values/52476 "2020-12-27T20:30:21Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![rcesarpacheco](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rcesarpacheco/32/20585_2.png) [@rcesarpacheco](https://discourse.julialang.org/u/rcesarpacheco)
#### Post date: [December 27, 2020, 8:30pm UTC](https://discourse.julialang.org/t/replace-for-loop-with-vectorized-call-of-a-function-that-returns-multiple-values/52476/1 "2020-12-27T20:30:21Z")

</div>

I have the following function: `problema_firma_emprestimo(r,w,r_emprestimo,posicao,posicao_banco)` , where all inputs are scalars. This function return three different matrix, using  
`return demanda_k_emprestimo,demanda_l_emprestimo,lucro_emprestimo`

I need to run this function for a series of values of posicao\_banco that are stored in a vector. I’m doing this using a for loop, because I need three separate matrix with each of them storing one of the three outputs of the function, and the first dimension of each matrix corresponds to the index of posicao\_banco. My code for this part is:

```julia
demanda_k_emprestimo = zeros(num_bancos,na,ny);
demanda_l_emprestimo = similar(demanda_k_emprestimo);
lucro_emprestimo = similar(demanda_k_emprestimo);
for i in eachindex(posicao_bancos)
    demanda_k_emprestimo[i,:,:] , demanda_l_emprestimo[i,:,:] , lucro_emprestimo[i,:,:] = problema_firma_emprestimo(r,w,r_emprestimo[i],posicao,posicao_bancos[i]);
end
 

```

Is there a fast and clean way of doing this using vectorized functions? Something like problema\_firma\_emprestimo.(r,w,r\_emprestimo[i],posicao,posicao\_bancos) ?

When I do this, I got a tuple with the result, but I can’t find a good way of unpacking the answer. Thanks!

---

<div class="post-metadata">

### Author: ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)
#### Post date: [December 27, 2020, 8:51pm UTC](https://discourse.julialang.org/t/replace-for-loop-with-vectorized-call-of-a-function-that-returns-multiple-values/52476/2 "2020-12-27T20:51:35Z")

</div>

there’s no vectorization == faster rule in Julia (I assume the impression comes from using Numpy? Python loop is slow and Numpy functions call a C loop under the hood). But Julia loop is already fast.

Using for-loop for this seems reasonable to me.

To unpact a Tuple (or a Vector), you can do:

```julia
a,b,c = (1,2,3)

```

another tip may be to use `@view` if you want non-copy behavior.
