Tag Info

Hot answers tagged

11

This seems fast(er): Extract[a, Transpose[{v, Range@Length@v}]] Addendum Mr.Wizard's clean method Diagonal @ a[[v]] has a surprising property for those of us who think that packed arrays rank just below the wheel in the list of inventions for the sake of efficiency. For unpacked arrays a, it uses virtually no extra memory. Example Initialization. ...


7

Although apparently undocumented Replace and ReplaceAll work with Association and this combination is considerably faster than Map. Further it appears to be somewhat faster than using a Dispatch table as well. Update: it seems Lookup is faster still. See additional timing result. Setup: rules = Thread[Range @ 26 -> CharacterRange["a", "z"]]; asc = ...


4

Edit: please see Update below. Although I am self-answering, as stated, I am not satisfied with these approaches. Nevertheless they may be useful and they can serve as a benchmark for any new solutions. This is cleanest method I know, though sadly it is a true memory hog, and not fast either: Diagonal @ a[[v]] {100, 200, 30, 4, 5, 600, 7} More ...


1

You could do it with a sparse array: s = SparseArray[ MapThread[({#1, #2} -> 1) &, { Range[Length[v]], (v - 1)*Length[v] + Range[Length[v]] }], {Length[v], Times @@ Dimensions[a]}]; s.Flatten[a, 1] But sadly, Flatten will take a long time for large a. (If you could keep around Flatten[a] for many "queries", it might be ...


1

This could be fast. a[[v[[#]], #]] & /@ Range[Length@v];



Only top voted, non community-wiki answers of a minimum length are eligible