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
use meshgrid or ndgrid:
% example matrix
Matrix = magic(5)
[n m] = size(Matrix)
% or define the dimensions directly
n = 5;
m = 5;
[X,Y] = meshgrid(1:n,1:m) %\\ [Y,X] = ndgrid(1:n,1:m)
(the difference for your 2D case is that, Y and X are swapped. - use it according to your needs.)
From the documentation:
[X,Y] = meshgrid(xgv,ygv)replicates the grid vectorsxgvandygvto produce a full grid. This grid is represented by the output coordinate arraysXandY. The output coordinate arraysXandYcontain copies of the grid vectorsxgvandygvrespectively. The sizes of the output arrays are determined by the length of the grid vectors. For grid vectorsxgvandygvof lengthMandNrespectively,XandYwill haveNrows andMcolumns.
Well there is not much more to explain, meshgrid is used to create a regular grid from two vectors, usually "x" and "y" values in order to obtain suitable input data for a 3D/color-coded plot of z-data. If you assume your x and y to be the vectors [1 2 3 ... n] it does exactly what you need.
returns:
X =
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
Y =
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5