Morten
Morten

Reputation: 223

Save correlation output from loop to matrix

I have a setup that looks like below

for(V in (seq(1, 250, by = 5))){
   for(n in (seq(1, 250, by = 5))){

        # 1) Working Algorithm creating a probability 
             ie. vector in range [0:1] 

        # 2) Take the natural log of this probability 
        a <-  log(lag(Probability), base = exp(1))

        # 3) calculate price differences
        b <-  abs(diff(Price) -1)

        # 4) Then compute correlation between a and b
        cor(a, b) 

        # 5) Here I'd like to save this in the corresponding index of matrix
   }
}

So that I get a [V, n] sized matrix as output, that collects from each loop.

I have a few problems with this.

Thanks for your help. I hope this is clear enough.

Upvotes: 0

Views: 1977

Answers (2)

Arun
Arun

Reputation: 118799

For your second question (My second question is how I save this correlation output into a matrix generated for each loop?), you could initialise a matrix before the loop and store each computed correlation in the corresponding index like:

sz <- seq(1, 250, by = 5)
out_mat <- matrix(0, nrow=length(sz), ncol=length(sz))
# then continue with your for-loop
for (V in 1:length(sz)) {
    for(n in length(sz)) {
        # here instead of accessing V and n in computing probability
        # use sz[V] and sz[n]
        ...
        ...
        # after computing the correlation, here use V and n (not sz[V] or sz[n])
        out_mat[V, n] <- c # c holds the value of cor(a,b)
    }
 }

Upvotes: 2

Paul Hiemstra
Paul Hiemstra

Reputation: 60934

What you can do with -Inf is replace that by NA, for example:

x = runif(10)
x[3] = 1/0
> is.infinite(x)
 [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[is.infinite(x)] <- NA
> x
 [1] 0.09936348 0.66624531         NA 0.90689357 0.71578917 0.14655174
 [7] 0.59561047 0.41944552 0.67203026 0.03263173

And use the na.rm argument for sd:

>  sd(x, na.rm = TRUE)
[1] 0.3126829

Upvotes: 2

Related Questions