What is the best way to construct a matrix whose elements are precisely their indices in Matlab?
EDIT: There is an answer to this question is applicable to how to build a matrix whose elements are functions of their indices. So I added it to the title question.
The format can be either a matrix with vectors as elements, or two molds, each of which stores one index.
In the end I would like to create a matrix whose elements are functions of their indices. Therefore, it is an effective method for this (but possibly different). Any comments on the effectiveness of welcome.
Matrix size tends to be large (the size of the squares of hundreds at least) for my application. As a result, techniques that use their own Matlab functions are likely to be much better than for cycles / while.
For example, for the size of the matrix [2 2] I would like to make any
IND = [1 1] [1 2] [2 1] [2 2]
or
X = 1 1 2 2 Y = 1 2 1 2
In the end I hope to do something like
matrixIneed = arrayfun(@(s)..., IND)
where s - 2 or the vector size
matrixIneed = arrayfun(@(i,j)..., X,Y)
Last preferable.
EDIT: Note on the accepted answer.
I took Andrew answer, because it is intuitive for me, and the code seems to be fast (at least for me).
If you've ever answered this question on Google, you're probably worried about how I do it. (Otherwise, if not the best practice, anyone can think of a double loop to complete the task.)
If so, you are advised to view the Andrew comment about the function reshape() , and Rody response performance meshgrid() and loops .
Nevertheless, the decision to pass to meshgrid() is a useful model for studying the function of meshgrid() . This is useful in many other Matlab functions.
Jigg repmat() can help you.