5

Perhaps a very easy question but I posted this on the Wolfram Community and didn't get any answer..

Suppose I have data like:

data = Table[{{Subscript[a, x, 1, 1], Subscript[a, x, 1, 2], 
    Subscript[a, x, 1, 3]}, {Subscript[b, x, 2, 1], Subscript[b, x, 2,
     2], Subscript[b, x, 2, 3]}}, {x, 1, 3}]

enter image description here

Now suppose I wan't to get from all rows the first item in the first list and the third item in the second list like:

enter image description here

It can be done by using:

{data[[All, 1, 1]], data[[All, 2, 3]]}\[Transpose]

or

{#[[1, 1]], #[[2, 3]]} & /@ data

But I'm wondering if there isn't an easier way by only using Part,Extract? It seems that going through the documentation the option only apply to one column (or more) but not to subparts in these columns.

Any thoughts?

Lou
  • 3,822
  • 23
  • 26

3 Answers3

6

My favorite being a slight variation of @Lou's own solution

Transpose[{data[[;;, 1, 1]], data[[;;, -1, -1]]}]

you can also use

Transpose@Rest@Extract[data, {{}, {;; , 1, 1}, {;; , -1, -1}}]
(* version 9 only -- does not work in version 10 -- thanks: Simon Woods *)

or

ReplacePart[data, p_ :> {data[[p, 1, 1]], data[[p, -1, -1]]}]

or

{First@First@#, Last@Last@#} & /@ data

or

ClearAll[f];
f[{{a_, __}, {__, b_}}] := {a, b}
f /@ data

all give

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896
4

My try

{#1[[1]], #2[[-1]]} & @@@ data

or

data /. {{f_, __}, {__, l_}} -> {f, l}
Junho Lee
  • 5,155
  • 1
  • 15
  • 33
3

I don't think there is any way to do it using just Part or Extract. With these functions you specify the elements you want at level 1, then at level 2, then level 3 etc. At each level you may specify a single element, a list of elements, All or a Span. There is no syntax for specifying different sub-parts for each of the elements selected at a certain level.

For an alternative, I suggest using the operator form of Extract along with Map:

Extract[{{1, 1}, {2, 3}}] /@ data
Simon Woods
  • 84,945
  • 8
  • 175
  • 324