Consider lists of vectors of elements like

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:





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


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.

  • 1
    $\begingroup$ Love it when a mod ends up in the LQ review. :) $\endgroup$ – Michael E2 Nov 23 '18 at 21:45
  • $\begingroup$ @MichaelE2 ok, explanation added. $\endgroup$ – Kuba Nov 23 '18 at 21:53
  • $\begingroup$ I approved it anyway. It's not always clear that excessive exposition would be an improvement. $\endgroup$ – Michael E2 Nov 23 '18 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 Nov 23 '18 at 23:35
  • 1
    $\begingroup$ @Kagaratsch right, you mentioned it. I edited the code. $\endgroup$ – Kuba Nov 24 '18 at 0:27


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}}}


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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