How to best construct a matrix whose elements are exactly their indices or functions of the indices in Matlab?

前端 未结 5 640
陌清茗
陌清茗 2020-12-02 00:18

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

5条回答
  •  渐次进展
    2020-12-02 01:14

    Have a look at the ind2sub, sub2ind, and reshape functions. They're useful for transforming subscripts and indexes on multidimensional arrays.

    In your case, it looks like you want this. (I think you want "subscripts" instead of "indices". Matlab uses "index" to mean the "linear" index of an element when viewing the array as a one-dimensional vector, and "subscripts" to mean the position along each dimension of a multidimensional array.)

    sz = [3 3];  % Size of your matrix
    n = prod(sz); % Total number of elements in matrix
    [X, Y] = ind2sub(sz, 1:n);  % Subscripts, returned as vectors
    X = reshape(X, sz);  % Reshape the subscript vectors to match your matrix
    Y = reshape(Y, sz);
    

    The meshgrid approach that @thewaywewalk gave will produce the same output, but I think the ind2sub approach is a bit more readable in this case, since it's worded in terms of array indexing, which is your problem domain. And it will generalize to working on slices or arbitrary subsets of arrays, which meshgrid will not, and corresponds nicely to ind2sub for efficient operations going the other way. (It's worth learning meshgrid anyway though; it pops up in other locations.)

提交回复
热议问题