Efficient way to pick/delete a list of rows/columns in a matrix in Mathematica

前端 未结 2 1503
生来不讨喜
生来不讨喜 2020-12-17 05:04

This question is in a way a continuation of the question I asked here:Simple way to delete a matrix column in Mathematica to which @belisarius and @Daniel provided very help

2条回答
  •  情深已故
    2020-12-17 05:29

    Part directly supports lists of indices when slicing arrays. The following definitions exploit that:

    takeOperator[a_?MatrixQ, rows_List, cols_List] :=
      a[[rows, cols]]
    
    dropOperator[a_?MatrixQ, rows_List, cols_List] :=
     a[[##]]& @@ complementaryIndices[a, rows, cols]
    
    complementaryIndices[a_?MatrixQ, rows_List, cols_List] :=
      Complement @@@ Transpose @ {Range /@ Dimensions @ a, {rows, cols}}
    

    Example use:

    a = RandomInteger[1000, {5000, 5000}];
    First @ Timing @ takeOperator[a, Range[1, 5000, 2], Range[1, 5000, 2]]
    (* 0.016 *)
    
    First @ Timing @ dropOperator[a, Range[1, 5000, 2], Range[1, 5000, 2]]
    (* 0.015 *)
    

提交回复
热议问题