Re: [R] How to remove double loop?

From: Ray Brownrigg <Ray.Brownrigg_at_mcs.vuw.ac.nz>
Date: Thu, 20 Mar 2008 08:31:27 +1300

Read the posting guide (the bit about reproducible code):

> 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) + }
Error: object "Val" not found
>
> 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])
+     }
+ }

Error: object "p" not found
>

On Thu, 20 Mar 2008, Jonas Malmros wrote:
> 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?



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. Received on Wed 19 Mar 2008 - 19:33:39 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 19 Mar 2008 - 20:30:23 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive