I'm used to MATLAB so this might be a stupid question but Mathematica is freaking me out.

I have a big matrix with the following format:

M = {{A,B,C},{1,{1,3,6,7},0},{1,{3,7,9},1}}

As you can see, each element in the second column is a separate list again. These separate lists contain integers, so it's no problem to get back to them. For example if I use MemberQ[M[[2,2]],1] it returns True, as it's supposed to do.

What I want to do now: my Matrix is a little longer, contains approx. 5'000 rows. I want to check every seperate list mentioned above for the appearance of a specific integer, as I did above with the MemberQ.

As a result it should give me something like the following (taking M as example): {True,False}.

I thought that's supposed to be easy with a for-loop as it is in MATLAB, but Mathematica always stops when condition is not met...

Looking forward to your answers. Please state if I need to clarify my question!

  • $\begingroup$ Please be precise in the problem description. The second row of this matrix is {1,{1,3,6,7},0}. The elements of the second row are not lists, contradicting what you said. memberQ[M[2,2],1] is not correct Mathematica code and won't return True. If you mean MemberQ[M[[2,2]],1], please write it as such. $\endgroup$
    – Szabolcs
    Commented Jun 14, 2014 at 13:21
  • $\begingroup$ Sorry for that, recognized it myself, already edited. Meant second column, and memberQ now correct. $\endgroup$
    – Phily
    Commented Jun 14, 2014 at 13:22
  • $\begingroup$ So B is a list then? $\endgroup$
    – Szabolcs
    Commented Jun 14, 2014 at 13:22
  • $\begingroup$ Not a Mma matrix (see MatrixQ) ... but a tensor. $\endgroup$
    – wolfies
    Commented Jun 14, 2014 at 13:23
  • $\begingroup$ Is MemberQ[#[[2]], 1] & /@ M what you are looking for? $\endgroup$
    – Öskå
    Commented Jun 14, 2014 at 13:24

1 Answer 1


All you need is to do Map MemberQ over the second column (a.k.a. [[2]]) of each lines:

M = {{A,B,C},{1,{1,3,6,7},0},{1,{3,7,9},1}}
MemberQ[#[[2]], 1] & /@ M

{False, True, False}

An equivalent would be (thanks to Mr.Wizard):

MemberQ[#2, 1] & @@@ M
  • 1
    $\begingroup$ Slightly cleaner and faster: MemberQ[#2, 1] & @@@ M (+1) $\endgroup$
    – Mr.Wizard
    Commented Jun 14, 2014 at 14:49
  • $\begingroup$ @Mr.Wizard I'm surprised that it's faster (haven't tried), but it's definitely more appealing to me. $\endgroup$
    – Szabolcs
    Commented Jun 14, 2014 at 15:31
  • $\begingroup$ @Szabolcs The statement only holds for unpacked data, but if we're working with packed data numeric methods are likely to be much faster (as I'm sure you know; stating it for others). $\endgroup$
    – Mr.Wizard
    Commented Jun 14, 2014 at 15:55

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.