3
$\begingroup$

Possibly it is duplicate, still I could not find here elegant way to remove matrix columns basing on binary sequence. i.e. if I apply {1,1,0,0,1,0,1} to matrix it should delete columns 3,4 and 6.

$\endgroup$
  • 5
    $\begingroup$ You can simply use matrix[[All, Pick[Range@Last@Dimensions@matrix, mask, 1]]], where matrix is your matrix, and mask is in your case {1,1,0,0,1,0,1}. $\endgroup$ – Leonid Shifrin Jun 27 '16 at 18:38
  • 3
    $\begingroup$ Another option: matrix[[All, Flatten[Position[{1, 1, 0, 0, 1, 0, 1}, 1]]]] $\endgroup$ – Coolwater Jun 27 '16 at 18:52
  • 3
    $\begingroup$ Also, Pick[Transpose[matrix], {1, 1, 0, 0, 1, 0, 1}, 1] // Transpose $\endgroup$ – Bob Hanlon Jun 27 '16 at 19:20
  • 1
    $\begingroup$ Similar to @BobHanlon's: Pick[matrix, Table[{1, 1, 0, 0, 1, 0, 1}, {Length@matrix}], 1]. Or, just to be safe: Pick[matrix, Table[PadRight[{1, 1, 0, 0, 1, 0, 1}, Last@Dimensions@matrix], {Length@matrix}], 1]. $\endgroup$ – march Jun 27 '16 at 20:37
  • 1
    $\begingroup$ Also for Mathematica 10 or higher: matrix[[;; , PositionIndex[{1, 1, 0, 0, 1, 0, 1}][1]]] $\endgroup$ – user1066 Jun 16 '17 at 12:32
3
$\begingroup$

Various solutions were posted in comments:

matrix = RandomInteger[10, {3, 7}];
mask = {1, 1, 0, 0, 1, 0, 1};

(* Leonid Shifrin *)
matrix[[All, Pick[Range@Last@Dimensions@matrix, mask, 1]]]

(* Coolwater *)
matrix[[All, Flatten[Position[mask, 1]]]]

(* Bob Hanlon *)
Pick[Transpose[matrix], mask, 1] // Transpose

(* march *)
Pick[matrix, Table[mask, {Length@matrix}], 1]

(* Alexey Popkov (for Mathematica 10 or higher) *)
Extract[matrix, {All, Flatten@Position[mask, 1]}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.