MATLAB - extracting rows of a matrix

后端 未结 5 819
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 14:26

a = [1 2; 3 4; 5 6] I want to extract the first and third row of a, so I have x = [1; 3] (indices of rows).

a(x)

相关标签:
5条回答
  • 2020-11-28 14:58

    Like this: a([1,3],:)

    The comma separates the dimensions, : means "entire range", and square brackets make a list.

    0 讨论(0)
  • 2020-11-28 15:08

    you could write a loop to iterate across the rows of the matrix:

    for i = [1,3]
        a(i,:)
    end
    
    0 讨论(0)
  • 2020-11-28 15:20

    In MATLAB if one parameter is given when indexing, it is so-called linear indexing. For example if you have 4x3 matrix, the linear indices of the elements look like this, they are growing by the columns:

    1   5   9
    2   6  10
    3   7  11
    4   8  12
    

    Because you passed the [1 3] vector as a parameter, the 1st and 3rd elements were selected only.

    When selecting whole columns or rows, the following format shall be used:

    A(:, [list of columns])  % for whole columns
    A([list of rows], :)     % for whole rows
    

    General form of 2d matrix indexing:

    A([list of rows], [list of columns])
    

    The result is the elements in the intersection of the indexed rows and columns. Results will be the elements marked by X:

    A([2 4], [3 4 5 7])
    
    . . C C C . C
    R R X X X R X
    . . C C C . C
    R R X X X R X    
    

    Reference and some similar examples: tutorial on MATLAB matrix indexing.

    0 讨论(0)
  • 2020-11-28 15:23

    type this: a([1 3],[1 2]) the output is

    ans =
         1     2
         5     6
    
    0 讨论(0)
  • 2020-11-28 15:24

    x = a([1 3]) behaves like this:

    temp = a(:)     % convert matrix 'a' into a column wise vector
    x = temp([1 3]) % get the 1st and 3rd elements of 'a'
    
    0 讨论(0)
提交回复
热议问题