[R] How to remove double loop?
davidr at rhotrading.com
davidr at rhotrading.com
Wed Mar 19 19:14:52 CET 2008
Jonas,
Take a look at CRRBinomialTreeOption{fOptions} in which Diethelm Wuertz
uses a double loop,
but of course, he's optimized it to use only a vector instead of a
matrix!
David L. Reiner, PhD
Head Quant
Rho Trading Securities, LLC
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Jonas Malmros
Sent: Wednesday, March 19, 2008 9:04 AM
To: r-help at r-project.org
Subject: [R] How to remove double loop?
Bill, Alberto, Gabor,
Thank you for answering my question. Now I learned about outer()
function.
That was a straightforward example.
But what if I had a matrix, where the last column was filled with
values first (again, a for loop), and the rest was filled by using a
double loop?
OVal <- matrix(0, n+1, n+1)
for(i in 0:n){
OVal[i+1, n+1] <- max(Val[i+1, n+1]-K, 0)
}
for(i in seq(n,1, by=-1)){
for(j in 0:(i-1)){
OVal[j+1, i] <- a*((1-p)*OVal[j+1, i+1]+p*OVal[j+2, i+1])
}
}
Even if I leave the first simple for loop as it is, is there a more
efficient way to program the double loop part now that OVal is used
within the function itself?
It is pretty easy to write for loops, but it is very hard to write
computationally optimal code. :-( Could you please help me with the
above one, if possible?
--
Jonas Malmros
Stockholm University
Stockholm, Sweden
______________________________________________
R-help at 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.
More information about the R-help
mailing list