title: How to best construct a matrix whose elements are exactly their indices or functions of the indices in Matlab?
body: <p>What is the best way to construct a matrix whose elements are exactly their indices in Matlab?</p>
  
  <hr>
  
  <p>EDIT: The existing answers to this question is applicable to how to construct a matrix whose elements are <em>functions</em> of their indices. So I added that to the question title.</p>
  
  <hr>
  
  <p>The format can be either a matrix with vectors as elements, or as two matrices each storing one index.</p>
  
  <p>At the end, I would like to create a matrix whose elements are functions of their indices. So an efficient method for that (but possibly different) is very much appreciated. Any comment on efficiency is welcomed.</p>
  
  <p>The size of matrices tends to be large (dimension of hundreds squared at the minimum) for my applications. As a result, methods that take advantage of native Matlab functions are probably much better than for/while loops. </p>
  
  <p>For example, for a matrix of size [2 2], I would like to make either</p>
  
  <pre><code>IND = 
  [1 1]  [1 2]
  [2 1]  [2 2]
  </code></pre>
  
  <p>or</p>
  
  <pre><code>X = 
  1 1
  2 2
  Y =
  1 2
  1 2
  </code></pre>
  
  <p>At the end, I am hoping to do something like </p>
  
  <pre><code>matrixIneed = arrayfun(@(s)..., IND)
  </code></pre>
  
  <p>where s is a vector of size 2, or </p>
  
  <pre><code>matrixIneed = arrayfun(@(i,j)..., X,Y)
  </code></pre>
  
  <p>The latter is preferred.</p>
  
  <hr>
  
  <p>EDIT: A note about accepted answer.</p>
  
  <p>I have accepted Andrew's answer because it is intuitive to me and the code seems quick (at least to me).</p>
  
  <p>If you ever Google an answer to this question, you are likely concerned about performance like I do. (Otherwise if not for best practice, anyone can think of a double loop to accomplish the task.)</p>
  
  <p>If so, you are encouraged to examine Andrew's comment on the <code>reshape()</code> function and Rody's answer about the performance of <code>meshgrid()</code> and <code>loops</code>.</p>
  
  <p>Nevertheless, thewaywewalk's solution with <code>meshgrid()</code> is a helpful example to learn the <code>meshgrid()</code> function. And it is useful in many other Matlab functions.</p>
  
  <p>Jigg's <code>repmat()</code> solution may help you too. </p>