[R] How to remove double for loop?
Alberto Monteiro
albmont at centroin.com.br
Wed Mar 19 13:45:01 CET 2008
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
More information about the R-help
mailing list