Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting data from a table in mathematica

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.

like image 566
kate Avatar asked Jun 19 '26 10:06

kate


2 Answers

An alternative that uses replacement rules is

ImportString["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", "Table"];
Partition[Flatten[%], 2]
% /. {___, x : {_, _?(# >= 100 &)}, ___} :> x

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 use Partition.

like image 144
Simon Avatar answered Jun 24 '26 15:06

Simon


You can also use a simple NestWhile

data = {{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}};
NestWhile[# + 1 &, 1, data[[#, 2]] < 100 &] - 1
like image 23
MarkV Avatar answered Jun 24 '26 14:06

MarkV