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

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:

``````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!

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:

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

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

5 Likes