Jonas Malmros wrote: > > I use double for loops to fill in matrices, but there are surely > better (and computationally faster) ways to perform that task. > Could someone show me, given the following example of a double for > loop, how this could be done? It is much easier to learn by examples. > > Val <- matrix(0, nrow=n+1, ncol=n+1) > for( i in 0:n){ > for(j in 0:i){ > Val[j+1, i+1] <- u^j*d^(i-j) > } > } > You could use outer. Val <- outer(vector1, vector2) does the tensor product, meaning that each Val[i,j] will be vector1[i] * vector2[j].
In this case, instead of the product, you should compute the expression: f <- function(j,i) { u^j * d^(i-j) } but only when j <= i. So, the function is: f <- function(j,i) { ifelse(j > i, 0, u^j * d^(i-j) } and the code becomes: Val <- outer(0:n, 0:n, f) "Entities should not be needlessly multplied" (Occam's Razor), so let's do it without the explicit mention of f: Val <- outer(0:n, 0:n, function(j,i) ifelse(j > i, 0, u^j*d^(i-j))) (if u and d are positive integers, there might be a much faster way of filling Val, using matrix multiplication and rounding down) Alberto Monteiro ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.