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

前端 未结 5 638
陌清茗
陌清茗 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:06

    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 vectors xgv and ygv to produce a full grid. This grid is represented by the output coordinate arrays X and Y. The output coordinate arrays X and Y contain copies of the grid vectors xgv and ygv respectively. The sizes of the output arrays are determined by the length of the grid vectors. For grid vectors xgv and ygv of length M and N respectively, X and Y will have N rows and M columns.

    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
    

提交回复
热议问题