I'm trying to write a function that will take select the first element in the table that satisfies a criteria. For example, if I am given the following table with times in the first column and number of people infected with a disease in the second, I want to write an argument that will return the time where at least 100 people are infected.
0 1
1 2
2 4
3 8
4 15
5 29
6 50
7 88
8 130
9 157
10 180
11 191
12 196
13 199
14 200
So from this table, I want the arguemnt to tell me that at 8 seconds, at least 100 people were infected. I tried using SELECT to do this, but I'm not sure how to use SELECT with a table of 2 columns and have it return a value in the first column based on criteria from the second column.
Here are a few different ways to do this, assuming I've interpreted your data correctly...
I suggest you read up on Part[] to understand this better.
An alternative that uses replacement rules is
The algorithm with which Mathematica searches for patterns ensures that this will return the first such case. If you want all cases then you can use ReplaceList. I suggest you read the tutorial on Patterns and Rules.
Edit:
ImportString
works on the newly formatted data as well - but you no longer need to usePartition
.I believe there is a faster way than what has already been given, but first, Joshua's
Cases
method can be made a little faster by using/;
rather than&
for the test.This is the solution I propose (edit: adding white space for clarity, since the double brackets do not format here):
Here are timings for the various methods offered. Please note that the
/.
method is only being run once, while the others are being runloops
times. Therefore, in this first test it is 100x slower than thePosition
method. Also, theNestWhile
method is only returning an index, rather than an actual first column element.With a longer table (I leave out the slow method):
Finally, confirmation of agreement:
You can also use a simple NestWhile