Optimize concatenation in Julia
<p>I have a very simple function written in Julia that needs to be run millions of times.</p>

<p>Code:</p>

<pre><code>function randfunc()
  #rands could be a global variable if desired
  rands = rand(200,100000)
  for i=1:100000
    #the alphabet can continue (and in Q1 as well)
    # rand(1:100000) generates a random number within the number of columns in rands
    a = rand(1:100000) 
    b = rand(1:100000)
    c = rand(1:100000)
    d = rand(1:100000)
    e = rand(1:100000)
    Q1 = hcat(rands[:,a],rands[:,b],rands[:,c],rands[:,d],rands[:,e])
    Q2 = *(Q1.',Q1)
  end
end
</code></pre>

<p>Is there any way to speed up the hcat function or replace it with something more efficient?</p>

<p>Another way to speed up this function would be to manually do the matrix multiplication without constructing the Q1 matrix, but the built-in <code>*(,)</code> operator runs faster than using <code>+</code>'s and <code>*</code>'s, at least on my attempt, and doing this seems to have more overhead than simply constructing Q1.</p>

<p>Using <code>rands = convert(Array{Float32}, rands)</code> helps a bit, but <code>Float16</code> is actually worse (especially for matrix multiplication). The elements in <code>rands</code> cannot be strictly integers, and the number of column vectors is arbitrary in Q1.</p>

<p>Edit: The initial concept of this question was to try to obtain a quick way of calling a matrix from data that would later be part of a matrix multiplication with its transpose. I have edited the code to try to address any ambiguity. </p>

<p>Old Code:</p>

<pre><code>function randfunc()
  #rands could be a global variable if desired
  rands = rand(200,100000)
  for i=1:100000-1
    Q1 = hcat(rands[:,[i]],rands[:,[i]].*rands[:,[i+1]])
    Q2 = *(Q1.',Q1)
  end
end
</code></pre>