5
$\begingroup$

I want to specify an element in a matrix and get all the elements in the diagonal of the element.

For example: $$\left( \begin{array}{cccc} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ \end{array} \right)$$

when I specify an element 7 in the above matrix, I can get all the elements {4,7,10} in the reverse diagonal of the element.

When the specified matrix elements have duplicates, the multiple lists of the opposite diagonals of containing the specified element are output.

Diagonal[Reverse@({
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
   }), 0 - 2]
$\endgroup$
6
$\begingroup$

A slightly different formulation and output from Alan's method:

fn[a_?MatrixQ, x_] :=
  a ~Reverse~ 2 /. b_ :> (Diagonal[b, #2 - #] & @@@ Position[b, x])

Test:

Mod[Range@40, 12] ~Partition~ 8 // MatrixForm

fn[%, 7]

$\begin{array}{cccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 0 & 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 & 9 & 10 & 11 & 0 \\ 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 0 & 1 & 2 & 3 & 4 \\ \end{array}$

{{7, 2, 9, 4, 11}, {5, 0, 7, 2, 9}, {0, 7, 2}}

Related:

| improve this answer | |
$\endgroup$
8
$\begingroup$
reverseDiagonal[mA_, x_] := With[{mR = Reverse@mA},
  Diagonal[mR, #] & /@ Apply[Minus@*Subtract, Position[mR, x], 2]
  ]
reverseDiagonal[{{1, 2, 3, 4}, {5, 6, 7, 7}, {9, 10, 11, 12}}, 7]
(* {{10, 7, 4}, {11, 7}} *)

You may want to map Reverse across the lists in this result.

| improve this answer | |
$\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.