1
$\begingroup$

How to return matching sublists or empty list

m1 = {{1, 0.5}, {2, 0.4}, {3, 0.1}};
m2 = {{1, 0.5}, {0, 0.4}, {0, 0.1}};
Commonest[Join[m1, m2]] 

out:

{{1, 0.5}}

But it fails to return 0 or empty list as the lists do not match

m1 = {{1, 0.5}, {2, 0.4}, {3, 0.1}};
m2 = {{0, 0.5}, {0, 0.4}, {0, 0.1}};
Commonest[Join[m1, m2]] 

out:

{{1, 0.5}, {2, 0.4}, {3, 0.1}, {0, 0.5}, {0, 0.4}, {0, 0.1}}

how to return empty list?

$\endgroup$
1
  • $\begingroup$ Perhaps If[(c = Commonest[Join[m1, m2]]) === Join[m1, m2], {}, c]? $\endgroup$ Dec 4, 2013 at 8:08

2 Answers 2

2
$\begingroup$
Intersection[m1,m2]

will deal with common elements and return "empty set" if no common elements. More complex list structures may require modification.

$\endgroup$
0
$\begingroup$

Try the following.

This are your lists to try on:

m1 = {{1, 0.5}, {2, 0.4}, {3, 0.1}};
m2 = {{1, 0.5}, {0, 0.4}, {0, 0.1}};
m3 = {{2, 0.5}, {0, 0.4}, {0, 0.1}};
m4 = {{1, 0.5}, {2, 0.4}, {0, 0.1}};

This is the function to do the job on one element:

f[x_] := Select[m1, #1 == x &];

    f[{1, 0.5}]

   (*  {{1, 0.5}} *)

This is how it works on the list:

Flatten[f /@ m2, 1]

(*  {{1, 0.5}} *)

then

Flatten[f /@ m4, 1] 

 (* {{1, 0.5}, {2, 0.4}}  *)

and

Flatten[f /@ m3, 1] 

 (*  {}  *)

Have fun.

$\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.