Reputation: 1932
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?
Upvotes: 2
Views: 602
Reputation: 173577
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.
Upvotes: 2