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.

This question already has an answer here:

I would like to divide element 1 of a list by element 2; element 2 by element 3, and so on. What is the best way of doing this?

I have tried

f = #1/#2 &

Have a feeling I might have to use Do, or Reap / Sow but don't have any programming background, so coming unstuck.

share|improve this question

marked as duplicate by Kuba, belisarius, bobthechemist, Sjoerd C. de Vries, Michael E2 Dec 19 '13 at 0:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Ratios is almost your friend :) –  Öskå Dec 18 '13 at 15:46
    
@ Öskå - thanks - indeed it is! –  martin Dec 18 '13 at 15:48
    
1/# & /@ Ratios@list is even more your friend ;o) –  Öskå Dec 18 '13 at 15:50
1  
@Öskå, or maybe just 1/Ratios@list –  Simon Woods Dec 18 '13 at 15:54
2  
Completing OP's form: f = (#1/#2 &) @@@ Partition[#, 2, 1] & –  Chris Degnen Dec 18 '13 at 17:23

3 Answers 3

up vote 13 down vote accepted

Operations on adjacent pairs of elements comes up often in , although I can't recall a specific question on this. Sometimes you get lucky with a built in function like Ratios or Differences that does exactly what you want. But what if there isn't a built-in function for your specific need?

The idiom you need to remember that will be useful for any arbitrary function (not just division or subtraction) is to use Most and Rest:

list = Range@10;
Most@list/Rest@list    
(* {1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9, 9/10} *)
share|improve this answer
2  
Worth to mention that Partition[list,2,1] may be useful but in this case it is longer. Maybe the title can be changed so it will become a refference Q&A for operations on adjacent elements? –  Kuba Dec 18 '13 at 16:43

Just for comparison:

list = Range[1000];

Do[ Divide @@@ Partition[list, 2, 1]                     , {1000}] // Timing // First
Do[ 1/Ratios@list                                        , {1000}] // Timing // First
Do[ Most@list/Rest@list                                  , {1000}] // Timing // First
Do[ #/#2 & @@@ Partition[list, 2, 1]                     , {1000}] // Timing // First
Do[ Developer`PartitionMap[Divide @@ # &, list, 2, 1]    , {1000}] // Timing // First
Do[ #[[1]]/#[[2]] & /@ Partition[list, 2, 1]             , {1000}] // Timing // First
Do[ Developer`PartitionMap[#[[1]]/#[[2]] &, list, 2, 1]  , {1000}] // Timing // First
1.045207
1.154407
0.982806
2.402415
3.151220
4.196427
4.087226
share|improve this answer
Most[#1/#2] &[list, RotateLeft[list]]
share|improve this answer

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