Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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).

share|improve this question
1  
Your last few questions have made me curious: what is your actual problem that has you dealing with lists of lists with different lengths? –  J. M. Sep 5 '12 at 9:14

2 Answers 2

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]}} *)
share|improve this answer
    
I'd have done odds = Range[1, 2 Length[data] - 1, 2] myself... –  J. M. Sep 5 '12 at 8:24
    
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)]? –  WayneGacy Sep 5 '12 at 8:27
    
@WayneGacy Just change the function Greater to what you need. –  b.gatessucks Sep 5 '12 at 8:29
    
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! –  WayneGacy Sep 5 '12 at 8:40
    
@WayneGacy Please see edit. –  b.gatessucks Sep 5 '12 at 9:08

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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