2
$\begingroup$

I have a list of lists that are not of the same length (for example, {{6}, {14}, {6, 26, 30}}), but I have to compare every element in the $n^{\text{th}}$ sublist with the corresponding $n^{\text{th}}$ odd number. So, 6 in the first sublist with 1 (first odd number), 14 in the second sublist with 3 (second odd number), 6 with 5 (third odd number), 26 with 5, 30 with 5, etc.

I tried to make another list with odd numbers, but I really don't know how to program the case when the comparison is with only one element in the sublist (e.g. sublists 1 and 2) and with multi-element sublists (e.g., 3rd sublist).

$\endgroup$
  • 1
    $\begingroup$ Your last few questions have made me curious: what is your actual problem that has you dealing with lists of lists with different lengths? $\endgroup$ – J. M. will be back soon Sep 5 '12 at 9:14
11
$\begingroup$

MapIndexed is your friend :) The part specification for each of the sublists is supplied as a second argument to the function being mapped. With this, you can construct your $n^{\text{th}}$ odd number to compare against. For example:

list = {{6}, {14}, {6, 26, 3}, {5, 10}};
MapIndexed[Thread[# > First@(2 #2 - 1)] &, list]
(* {{True}, {True}, {True, True, False}, {False, True}} *)

Replace > (Greater) with < (Less) or == (Equal) or any other comparison function as per your needs.

$\endgroup$
2
$\begingroup$

Something like :

data = {{6}, {14}, {6, 2, 30}};

odds = 2 # + 1 & /@ Range[0, Length[data] - 1];

MapThread[Thread[Greater[#1, #2]] &, {data, odds}]

(* {{True}, {True}, {True, False, True}} *)

If the condition is :

cond[x_, y_] := If[x > y, Pi y, 0]

then one needs to wrap it with Unevaluated :

MapThread[Thread[Unevaluated[cond[#1, #2]]] &, {data, odds}]

(* {{\[Pi]}, {3 \[Pi]}, {5 \[Pi], 0, 5 \[Pi]}} *)
$\endgroup$
  • $\begingroup$ I'd have done odds = Range[1, 2 Length[data] - 1, 2] myself... $\endgroup$ – J. M. will be back soon Sep 5 '12 at 8:24
  • $\begingroup$ And if I don't want Mathematica to write {True, True} but to calculate something with numbers that satisfy conditions? For example: If True, Print[\pi*(2k+1)]? $\endgroup$ – WayneGacy Sep 5 '12 at 8:27
  • $\begingroup$ @WayneGacy Just change the function Greater to what you need. $\endgroup$ – b.gates.you.know.what Sep 5 '12 at 8:29
  • $\begingroup$ MapThread[Thread[If[#1 == 3.14*#2, Print[#1]]] &, {data, odds}] {If[{6} == 3.14, Print[{6}]], If[{14} == 9.42, Print[{14}]], If[{6, 2, 30} == 15.7, Print[{6, 2, 30}]]} If I put that line in Mathematica, the output is like line above. I don't want to write that, only that sublist whose elements satisfy condition. THANK you! $\endgroup$ – WayneGacy Sep 5 '12 at 8:40
  • $\begingroup$ @WayneGacy Please see edit. $\endgroup$ – b.gates.you.know.what Sep 5 '12 at 9:08

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.