I have a 2-dim array. The first 3 rows have column headings. The heading can be a single word, or 2 words (which take 2 rows) or 3 words (which take 3 rows). For each column I know which row has the most meaningful name for that column. I can't figure out how to map this and get what I want. For example:

a1 = {{"", "", "Class"}, {"Year", "Full", "of"}, {"Sold", "Amount", 
a2 = {2, 3, 1};

I want my three headings to be "Year", "Amount", "Class", this is based on a2. I assume I can use Part to do this, and use Map with a LevelSpec. But I can't figure out how to make this work. Maybe I'm thinking in the wrong direction.


2 Answers 2


I would use one of these:

MapThread[Part, {a1\[Transpose], a2}]

MapIndexed[a1[[##]][[1]] &, a2]
{"Year", "Amount", "Class"}
  • $\begingroup$ I suppose you need to add a1[[;;3]] since this is only part of bigger matrix. $\endgroup$
    – Kuba
    Jun 18, 2014 at 21:31
  • $\begingroup$ @Kuba Sorry, what's the full input supposed to be then? $\endgroup$
    – Mr.Wizard
    Jun 18, 2014 at 21:33
  • $\begingroup$ I just think a1 contains not only the headers but all the data. But I'm not sure. "The first 3 rows have column headings". So with the [[;;3]] it should work. $\endgroup$
    – Kuba
    Jun 18, 2014 at 21:35
  • $\begingroup$ @Kuba - my real data has 20+ columns and a few hundred rows. That would be a1. a2 would have the same number of columns as a1. Sorry I just tried to simplify my example. And actually to make things worse, my real a1 has an additional first dimension. However adjusting for that first dimension, user15996's solution and both of Mr. Wizard's solutions work perfectly. As usual it will still take me a little time to understand Mr. Wizard's frighteningly elegant code. $\endgroup$ Jun 18, 2014 at 21:46
  • 1
    $\begingroup$ Thanks for the help and the offer, but it's more helpful for me to figure it out. If I get really stuck I'll take you up on your offer. $\endgroup$ Jun 18, 2014 at 21:49

Something like this?

pickHeading = MapThread[List, {a2, Range[Length[a2]]}]

(* {{2, 1}, {3, 2}, {1, 3}} *)

Extract[a1, #] & /@ pickHeading

(* {"Year", "Amount", "Class"} *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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