Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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", 
"business"}};
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.

share|improve this question

2 Answers 2

up vote 4 down vote accepted

I would use one of these:

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

MapIndexed[a1[[##]][[1]] &, a2]
{"Year", "Amount", "Class"}
share|improve this answer
    
I suppose you need to add a1[[;;3]] since this is only part of bigger matrix. –  Kuba Jun 18 at 21:31
    
@Kuba Sorry, what's the full input supposed to be then? –  Mr.Wizard Jun 18 at 21:33
    
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. –  Kuba Jun 18 at 21:35
    
@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. –  Mitchell Kaplan Jun 18 at 21:46
1  
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. –  Mitchell Kaplan Jun 18 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"} *)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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