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
Cmat
does not need to appear in my code, only the fact thatLenght[Cmat]==Lenght[B]
matters. $\endgroup$bsat = Extract[c, Position[b, x_ /; MemberQ[a, x]]]
$\endgroup$