Here is one possibility to compute the slope between each pair of adjacent points. I create a list of random points first and use the Sort
function sort them by their x-coordinate (First
):
list = SortBy[RandomReal[{0, 10}, {20, 2}], First]
{{0.0612793, 5.82737}, {0.171386, 6.8975}, {0.704354,
8.53224}, {0.798152, 6.39703}, {0.967127, 8.35358}, {1.75119,
6.73572}, {3.35177, 6.91908}, {3.81578, 7.8129}, {4.19851,
2.66794}, {4.73162, 3.37847}, {5.65875, 4.22096}, {5.80131,
8.62895}, {5.8604, 6.61611}, {6.24086, 3.4343}, {7.01985,
9.76974}, {7.76579, 1.96783}, {7.90587, 8.20642}, {8.65277,
2.30016}, {9.06088, 5.22962}, {9.98638, 6.34865}}
Then, the list of points is partitioned into lists of pairs using Partition
with an offset of 1. Now we can use a pure function to compute the slope and use Apply
to apply it to the list of pairs.
(Last[#2] - Last[#1])/(First[#2] - First[#1]) & @@@ Partition[list, 2, 1]
{9.71896, 3.06724, -22.7637, 11.5789, -2.06344, 0.114559, 1.92631,
-13.4428, 1.33282, 0.908702, 30.9207, -34.0611, -8.36311, 8.13291,
-10.4592, 44.5349, -7.90772, 7.1782, 1.20911}
This can also be done using the Map
function and indexing:
(#[[2, 2]] - #[[1, 2]])/(#[[2, 1]] - #[[1, 1]]) & /@ Partition[list, 2, 1]
{9.71896, 3.06724, -22.7637, 11.5789, -2.06344, 0.114559, 1.92631,
-13.4428, 1.33282, 0.908702, 30.9207, -34.0611, -8.36311, 8.13291,
-10.4592, 44.5349, -7.90772, 7.1782, 1.20911}
EDIT: a much faster version using Transpose
, Differences
and Apply
For sure there are several ways of dealing with this question. Here's much a faster version to compute the slope between adjacent points in a list using the functions Differences
, Transpose
and Apply
:
#2/#1 & @@ Transpose@Differences[list]
{9.71896, 3.06724, -22.7637, 11.5789, -2.06344, 0.114559, 1.92631,
-13.4428, 1.33282, 0.908702, 30.9207, -34.0611, -8.36311, 8.13291,
-10.4592, 44.5349, -7.90772, 7.1782, 1.20911}
When i apply this to a list of 10^6 pairs in list I get similar timings as the approach presented by Anon. When applied to 10^7 pairs in the list the first approach seems to be a bit faster compared to Anon's approach in most of the runs:
list = SortBy[RandomReal[{0, 10}, {10^6, 2}], First];
{Timing[#2/#1 & @@ Transpose@Differences[list]][[1]],
Timing[Flatten[Ratios[Differences[list], {0, 1}]]][[1]]}
{0.046800, 0.078001}
list = SortBy[RandomReal[{0, 10}, {10^7, 2}], First];
{Mean@Table[Timing[#2/#1 & @@ Transpose@Differences[list]][[1]], {i, 1, 25}],
Mean@Table[Timing[Flatten[Ratios[Differences[list], {0, 1}]]][[1]], {i, 1, 25}]}
{0.557860, 0.630868}
Partition[list, 2, 1]
$\endgroup$