title: Julia: How to extract a portion of an array along a specified dimension
body: <p>I am trying to figure out (in Julia) how to extract a portion of an array along a specified dimension, when the dimension itself is a variable. If the dimension is known it is straightforward to extract a portion of an array. For example, I can extract a portion along the 3rd dimension by doing something like this:</p>
  
  <pre><code>A = rand(27,33,11)
  A_portion = A[:,:,3:7]
  </code></pre>
  
  <p>Is there a compact/efficient method for extracting a portion of an array along a variable dimension? For example, something that looks like this?</p>
  
  <pre><code>A = rand(27,33,11)
  dim = 3  ## dimension along which to grab a portion of the array
  first_element = 3  ## first element over specified dimension
  last_element = 7  ## last element over specified dimension 
  A_portion = MyFunction(A,dim,first_sample,last_sample)
  </code></pre>
  
  <p>One possibility is to write a set of if-statements for every possible combination of array dimension (up to some maximum number of dimensions) and dimension along which to extract the portion. For example, something like this:</p>
  
  <pre><code>MyFunction(A::Array,dim::Int,first_element::Int,last_element::Int)
      if ndims(A)==1 &amp;&amp; dim==1
          return A[first_element:last_element]
      elseif ndims(A)==2 &amp;&amp; dim==1
          return A[first_element:last_element,:]
      elseif ndims(A)==2 &amp;&amp; dim==2
          return A[:,first_element:last_element]
      elseif ndims(A)==3 &amp;&amp; dim==1
          ...
          ...
          ...
  </code></pre>
  
  <p>Clearly this becomes quite messy in order to allow for arrays with large numbers of dimensions. Is there a more compact/efficient approach for doing this?</p>