# comparing lists of unequal lenghts

Suppose I have three (nested) lists A , B and Cmat where Length[A]!=Length[B] and Length[Cmat]==Length[B] (B and Cmat have equal Length but different elements). For each element of A, I want to check which elements of B satisfy the condition A[[i]]==B[[j]]. If this condition is met, I want to extract the elements of Cmat. I can do this using For loops:

bsat = {};
A = {{2, 4}, {2, 34}, {2, 36}, {3, 35}, {4, 34}};
B = {{2, 6}, {2, 34}, {2, 38}, {3, 35}, {4, 7}, {17, 52}, {4, 34},{3,90}};
Cmat = {{1, 0, 0, 0, 0}, {3, 0, 2, 5, 0}, {6, 0, 2, 1, 3}, {34, 55, 6,
21, 8}, {44, 2, 1, 54, 77}, {87, 2, 1, 4, 7}, {1, 3, 0, 45,
78}, {13, 45, 12, 56, 99}};

For[i = 1, i <= Length[A], i++, For[j = 1, j <= Length[B], j++,
If[A[[i]] == B[[j]], AppendTo[bsat, Cmat[[j]]]]]]
bsat
(* output *)
{{3, 0, 2, 5, 0}, {34, 55, 6, 21, 8}, {1, 3, 0, 45, 78}}


This works, but I cannot say I am proud of it. Is there a better "Mathematica" way to do this?

EDIT: question updated to provide explicit example

• @kglr Thanks for the comment, realized I needed to add info to the question, it's not that simple.
– geom
Jun 1 at 18:48
• @kglr Cmat does not need to appear in my code, only the fact that Lenght[Cmat]==Lenght[B] matters.
– geom
Jun 1 at 19:17
• You should provide a complete minimal working example so other people have something to work with. It will make it much more likely that you get help. Jun 1 at 19:18
• bsat = Extract[c, Position[b, x_ /; MemberQ[a, x]]] Jun 1 at 19:32
• @N.J.Evans I edited the code to provide a minimal working example, hope it helps
– geom
Jun 1 at 19:35

Extract[Cmat, Position[B, Alternatives @@ A]]