2

I have a long line of code and am trying to speed things up by removing for loops. As I under stand when you have multiple nested loops it can slow your code down. My original code contained 3 loops which ran for 598, 687 and 44 iterations. It took about 15 minutes to run. I use this code to display output from some models I'm running and waiting 15 minutes is unacceptable. I'm having trouble getting rid of one of the loops. I'm trying to use vectors but it doesn't run correctly. Lets look at the first 10 iterations.

#data
flows=c(-0.088227, 0.73024, 0.39683, 1.1165, 1.0802, 0.22345, 0.78272, 0.91673, 0.53052, 0.13852)
cols=c(31, 31, 30, 30, 30, 30, 31, 31, 31, 31)
rows=c(3, 4, 4, 5, 6, 7, 7, 8, 9, 10)
dataset=matrix(0,33,44)
for (i in 1:10){dataset[rows[i],cols[i]]<-flows[i]+dataset[rows[i],cols[i]]}

#And this is my alternative(Not working)
dataset=matrix(0,33,44)
NoR=10
dataset[rows[1:NoR],cols[1:NoR]]<-flows[1:NoR]+dataset[rows[1:NoR],cols[1:NoR]]

See the problem here. Somehow columns are showing the same row information. What am I missing here? Why won't the second code run correctly?

CCurtis
  • 1,770
  • 3
  • 15
  • 25

1 Answers1

2

It's a little hard to help with what is likely your real underlying problem, because I'm guessing we're only seeing a small snippet of your code here. But I think maybe you're looking for something like this:

flow_mat <- matrix(0,33,34)
flow_mat[(cols - 1) * 33 + rows] <- flows

Remember that matrices are just vectors with a dimension attribute. So you can index them just like a vector, imagining that the indices start at the "upper left" and wrap around by column.

joran
  • 169,992
  • 32
  • 429
  • 468
  • @ joran wow didn't realize you could call a matrix like that. I altered the code `flow_mat[(cols - 1) * 33 + rows] <- flows+flow_mat[(cols - 1) * 33 + rows]` There are several cells that have multiple values and they have to be added. You were right about it not speeding up the code. I'm thinking about posting the rest of my code would it be more appropriate to start a new question? – CCurtis Nov 16 '13 at 02:30
  • @CCurtis A new question would probably be best, but be sure to try identify a specific, self-contained piece of code that is slow. Ideally, we should be able to run it ourselves. – joran Nov 16 '13 at 02:42
  • @joran Ok I'll put something together. Will let you know when the question is up. Thanks for you help. – CCurtis Nov 16 '13 at 02:57
  • @joran I've posted my full code [here](http://stackoverflow.com/questions/20131446/r-code-slowing-with-increased-interations) It's a little faster than before but I found that run time in nonlinear. – CCurtis Nov 21 '13 at 20:59