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 list of lists from which I pick out the positions of the number 1 and then print out these positions for each list. I am having some trouble collecting what I am printing into a list / matrix / array though. Below is my list of lists and the commands by which I find the positions of the 1's and print them out. Thanks.

ZeroCrossings = {{0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1,
   0, 0, 1, 0, 0, 0, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1,
   0}, {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 
  0, 0, 1, 0, 0, 1, 1, 0}, {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0}}

Do[Print[Flatten[Transpose[Position[ZeroCrossings[[t]], 1]]]], {t, 1,Length[ZeroCrossings]}]

{3,9}

{4,5,8,12,13}

{4,12,13}

{4,8,11,13}

{4,9,12,13}

{5,6,11}

share|improve this question
1  
Drop the Print and change Do to Table. Is this what you need? –  Szabolcs Jul 22 at 4:11

3 Answers 3

up vote 1 down vote accepted

Primarily you just need to use Table instead of Do and Print. Also you can simplify the code:

Table[Flatten @ Position[t, 1], {t, ZeroCrossings}]
{{3, 9}, {4, 5, 8, 12, 13}, {4, 12, 13}, {4, 8, 11, 13}, {4, 9, 12, 13}, {5, 6, 11}}

See Case #2 of: Alternatives to procedural loops and iterating over lists in Mathematica

It may be simpler to use Map:

Flatten @ Position[#, 1] & /@ ZeroCrossings

This is probably a bit advanced for you right now but you could also use:

GatherBy[Position[ZeroCrossings, 1], First][[All, All, 2]]

Or if you are using Mathematica 10:

GroupBy[Position[ZeroCrossings, 1], First -> Last] // Values
share|improve this answer
    
Like you said first, I used Table in place of Do to solve my problem. Table[Flatten[Transpose[Position[ZeroCrossings[[t]], 1]]], {t, 1, Length[ZeroCrossings]}] Thanks for your help and advice! –  user3418425 Jul 22 at 4:16

Another approach:

ZeroCrossings = {{0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0,
     1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 
    0, 1, 1, 0}, {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 0,
     1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0}, {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 
    1, 0, 0, 0}};

Map[Last, GatherBy[Position[ZeroCrossings, 1], First], {-2}]

{{3, 9}, {4, 5, 8, 12, 13}, {4, 12, 13}, {4, 8, 11, 13}, {4, 9, 12,
13}, {5, 6, 11}}

share|improve this answer

You can also use PositionIndex in Version 10

(PositionIndex /@ ZeroCrossings)[[All, 2]]

Gives:

{{3, 9}, {4, 5, 8, 12, 13}, {4, 12, 13}, {4, 8, 11, 13}, {4, 9, 12, 13}, {5, 6, 11}}
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.