Find elements of array with largest absolute value
You could use SparseArray
to do this:
sa = SparseArray[H];
With[{ord = Reverse @ Ordering[Abs @ sa["NonzeroValues"], -5]},
Thread[{
sa["NonzeroValues"][[ord]],
sa["NonzeroPositions"][[ord]]
}]
]
{{2.67802 + 1.28002 I, {1, 2, 2}}, {-2.16128 + 0.250312 I, {3, 2, 1}}, {-0.907637 + 1.71577 I, {3, 3, 1}}, {-1.31683 - 1.21146 I, {1, 2, 3}}, {1.53659 + 0.686038 I, {1, 2, 1}}}
Let h
be the OP's H
, to avoid single capital letters:
ClearAll[next, arrayPos];
next[{{q_, r_}, d_}] := {QuotientRemainder[r, Times @@ Rest[d]], Rest[d]};
arrayPos[dims_][idx_] :=
NestList[step, {{0, idx - 1}, dims}, Length[dims]][[2 ;;, 1, 1]] + 1;
arrayPos[Dimensions@h] /@
Reverse@OrderingBy[Flatten@h, Abs, -5] //
Transpose[{Extract[h, #], #}] &
(*
{{2.67802 + 1.28002 I, {1, 2, 2}},
{-2.16128 + 0.250312 I, {3, 2, 1}},
{-0.907637 + 1.71577 I, {3, 3, 1}},
{-1.31683 - 1.21146 I, {1, 2, 3}},
{1.53659 + 0.686038 I, {1, 2, 1}}}
*)
This is shorter and maybe a bit faster than SparseArray
:
Ordering[- Flatten @ Abs @ H, top] //
Tuples[Range @ Dimensions @ H][[#]] & //
Thread[{Extract[H, #], #}] &
{ {2.67802 + 1.28002 I, {1, 2, 2}}, {-2.16128 + 0.250312 I, {3, 2, 1}}, {-0.907637 + 1.71577 I, {3, 3, 1}}, {-1.31683 - 1.21146 I, {1, 2, 3}}, {1.53659 + 0.686038 I, {1, 2, 1}} }