What is the best way to construct a matrix whose elements are exactly their indices in Matlab?
EDIT: The existing answers to this question is applicable to how
Get used to ndgrid. Avoid meshgrid, except in support of plotting and graphics operations.
The output of ndgrid, expressed in terms of rows, columns, etc., has more natural semenatics for MATLAB matrix operations than x,y coordinates, as returned by meshgrid.
>> nrows = 3;
>> ncols = 4;
>> [II,JJ] = ndgrid(1:nrows,1:ncols)
II =
1 1 1 1
2 2 2 2
3 3 3 3
JJ =
1 2 3 4
1 2 3 4
1 2 3 4
MATLAB's dimension ordering is rows as first dimension, columns as second, then higher dimensions. ndgrid follows this convention with the ordering of its inputs and outputs. For reference, the equivalent meshgrid command is [JJ,II] = meshgrid(1:ncols,1:nrows);.
An excellent illustration of why you should stick to the rows,columns frame of mind is converting to linear indexes: sub2ind. The function sub2ind expects subscripts ordered in the same way as the outputs of ndgrid:
>> inds = sub2ind([nrows ncols],II,JJ)
inds =
1 4 7 10
2 5 8 11
3 6 9 12
Formulating this command requires little thought if you are always thinking in terms of rows,columns (subscripts) rather than x,y.
Again, use ndgrid.