I recently wrote this line of code: for(i in seq_len(exponent)){out<-squareMat%*%out}
. Clearly, i
is never used and I just wanted to say "exponent
times, do out<-squareMat%*%out
". Was there a way to do this without the redundant counter i
? For example, is there an apply
family function for this?
Example - I have:
squareMat<-matrix(c(0,10,20,30),2,2)
out<-diag(nrow = nrow(squareMat))
exponent<-5
for(i in seq_len(exponent)){out<-squareMat%*%out}
out
What I want is:
squareMat<-matrix(c(0,10,20,30),2,2)
out<-diag(nrow = nrow(squareMat))
exponent<-5
[do exponent times]{out<-squareMat%*%out}
out
for
loops unless there are compelling reasons to do so. – Celtic1:2 + 3:4
is a for loop in C. There are sometimes where R vectorization makes for more concise code. There are other times when a simple loop can make more concise code. What’s more, youri
counter is not redundant, it’s use allows for the actual calculation to happen! – Graniela