Swapping rows and columns

后端 未结 2 1629
悲&欢浪女
悲&欢浪女 2021-02-05 16:48

I need a MATLAB function that will swap 2 rows or 2 Columns with each other in a matrix of arbitrary size.

2条回答
  •  失恋的感觉
    2021-02-05 17:41

    Say you take the matrix

    >> A = magic(4)
    A =
        16     2     3    13
         5    11    10     8
         9     7     6    12
         4    14    15     1
    

    If you want to swap, say, columns 3 and 1, you write

    >>A(:,[1 3]) = A(:,[3 1])
    
    A =
         3     2    16    13
        10    11     5     8
         6     7     9    12
        15    14     4     1
    

    The same works for swapping rows (i.e. A([4 2],:) = A([2 4],:) to swap rows 2 and 4).

提交回复
热议问题