2
$\begingroup$

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

$\endgroup$
5
  • $\begingroup$ @kglr Thanks for the comment, realized I needed to add info to the question, it's not that simple. $\endgroup$
    – geom
    Jun 1 at 18:48
  • $\begingroup$ @kglr Cmat does not need to appear in my code, only the fact that Lenght[Cmat]==Lenght[B] matters. $\endgroup$
    – geom
    Jun 1 at 19:17
  • 1
    $\begingroup$ 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. $\endgroup$
    – N.J.Evans
    Jun 1 at 19:18
  • 1
    $\begingroup$ bsat = Extract[c, Position[b, x_ /; MemberQ[a, x]]] $\endgroup$
    – N.J.Evans
    Jun 1 at 19:32
  • 1
    $\begingroup$ @N.J.Evans I edited the code to provide a minimal working example, hope it helps $\endgroup$
    – geom
    Jun 1 at 19:35

1 Answer 1

5
$\begingroup$
Extract[Cmat, Position[B, Alternatives @@ A]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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