3
$\begingroup$

Consider lists of vectors of elements like

list[1]={{a1,b1,c11},{a2,b2,c12},{a3,b3,c13},{a4,b4,c14},{a5,b5,c15}};
list[2]={{a1,b1,c21}            ,{a3,b3,c23},{a4,b4,c24},{a5,b5,c25}};
list[3]={{a1,b1,c31},{a2,b2,c32},{a3,b3,c33}            ,{a5,b5,c35}};

where the length 3 of vectors in lists is just an example and could be longer, and there may be more than 3 such lists.

I would like to have a function truncate[listoflists_] that takes all these lists and truncates them to only have the vectors containing ai,bi entries that are present in all of them:

{list[1],list[2],list[3]}=truncate[{list[1],list[2],list[3]}];
list[1]
list[2]
list[3]

{{a1,b1,c11},{a3,b3,c13},{a5,b5,c15}}

{{a1,b1,c21},{a3,b3,c23},{a5,b5,c25}}

{{a1,b1,c31},{a3,b3,c33},{a5,b5,c35}}

Is there a quick way to do this in Mathematica? Thanks for any suggestion.

$\endgroup$

2 Answers 2

3
$\begingroup$

It is short (does not mean quick) to get it via associations:

truncate = Values @ KeyIntersection @ Map[#[[;; 2]] -> # &, #, {2}] &

We convert {a1,b1,c11} to {a1,b1}->{a1,b1,c11} and everything else is straightforward.

$\endgroup$
5
  • 1
    $\begingroup$ Love it when a mod ends up in the LQ review. :) $\endgroup$
    – Michael E2
    Commented Nov 23, 2018 at 21:45
  • $\begingroup$ @MichaelE2 ok, explanation added. $\endgroup$
    – Kuba
    Commented Nov 23, 2018 at 21:53
  • $\begingroup$ I approved it anyway. It's not always clear that excessive exposition would be an improvement. $\endgroup$
    – Michael E2
    Commented Nov 23, 2018 at 22:00
  • $\begingroup$ I have changed it to truncate = Values@KeyIntersection@Map[{#[[1]], #[[2]]} -> # &, #, {2}] & to make it compatible with longer vector cases. $\endgroup$
    – Kagaratsch
    Commented Nov 23, 2018 at 23:35
  • 1
    $\begingroup$ @Kagaratsch right, you mentioned it. I edited the code. $\endgroup$
    – Kuba
    Commented Nov 24, 2018 at 0:27
1
$\begingroup$

Also

tF = Module[{i = Intersection@@#[[;;, ;;, #2]], k = #2}, Select[MemberQ[i, #[[k]]]&]/@ #]&

lists = list /@ {1, 2, 3};
tF[lists, {1, 2}]

{{{a1, b1, c11}, {a3, b3, c13}, {a5, b5, c15}},
{{a1, b1, c21}, {a3, b3, c23}, {a5, b5, c25}},
{{a1, b1, c31}, {a3, b3, c33}, {a5, b5, c35}}}

$\endgroup$

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.