1
votes

I'm hoping someone might be able to show me a more efficient way of writing my code in mathematica.

I've got a table which has a column of (absolute) times and a second column containing a string associated with that the period of time between the time on the same row and the time on the row below. These times are all regularly spaced. I also have a second list of irregular times and I want to have a list of the strings that would be associated with that time period.

I've done it using this code:

regulartime={{1800,a},{3600,b},{5400,b}}  
irregtime={2054,2817,3060,4594, 5123}


flooredtimes=Floor[irregtime,1800]  
position=Table[Position[regulartime,flooredtimes[[i]]],{i,Length[flooredtimes]}]  
lastlist=Table[regulartime[[position[[i,1,1]],2]],{i,Length[flooredtimes]}]  

This outputs a list {a,a,a,b,b} which I can then combine with my list of irregular times. My problem is that I am trying to do it for long (~500 000) lists and it takes a long time, is there a better way to do this?? Thanks in advance for any help!

2

2 Answers

2
votes

here are two ideas..

Function[ ireg, 
      Last@Last@
            Select[regulartime, #[[1]] == Floor[ireg, 1800] &]] /@ irregtime


(*{a, a, a, b, b}*)



Last@regulartime[[Floor[#, 1800]/1800]] & /@ irregtime

(*{a, a, a, b, b}*)
0
votes

Here is a variation on george's second method:

regulartime[[Quotient[#, 1800], 2]] & /@ irregtime
{a, a, a, b, b}

Be aware that you will get an error with values less than 1800; you may want to handle that separately:

time[x_ /; x >= 1800] := regulartime[[Quotient[x, 1800], 2]]
time[else_] := Missing[]

time /@ {356, 3060, 4594}
{Missing[], a, b}