forecaster
forecaster

Reputation: 1159

R programming with loops

I have the following 3x3 square matrix a and a vector x:

a = matrix(c(1.0, 0.1, 0.5, 
             0.1, 1.0, 0.9,
             0.5, 0.9, 1.0), nrow=3, ncol=3)

x = c(0.1,0.2,0.3)

I would like to following formula basically using the upper triangle of the matrix and vector

y = (a12 - (x1/x2)^2 + (a13 - x1/x3)^2 + (a23 - x2/x3)^2

I used the following for loop in R for the above formula, I getting the following error:

Error in a[i, j] : subscript out of bounds

I would greatly appreciate if you could please let me know if I'm doing anything incorrectly.

## initialize y
y = 0 

for (i in 1 : nrow(a)-1){
  for (j in i+1 : nrow(a)){
    y = y + ((a[i,j]) - (x[i]/x[j])^2
  }
}

Upvotes: 1

Views: 190

Answers (2)

Ferdinand.kraft
Ferdinand.kraft

Reputation: 12829

You can avoid the loop using this:

b <- a - outer(x,x,`/`)
sum(b[upper.tri(b)]^2)

Result

[1] 0.2422222

Upvotes: 11

Paul
Paul

Reputation: 27473

You are missing some parenthesis, otherwise n:m will define some unanticipated sequence which to R looks like any other vector and can interact with the other math.

Original code, with formula replaced by printing indexes:

for (i in 1 : nrow(a)-1){
+   for (j in i+1 : nrow(a)){
+ print(c(i,j))
+ }
+ }
[1] 0 1
[1] 0 2
[1] 0 3
[1] 1 2
[1] 1 3
[1] 1 4
[1] 2 3
[1] 2 4
[1] 2 5

Those 0s and 5s arent in range.

But if put parenthesis everywhere, it behaves:

for (i in (1 : (nrow(a)-1))){
+   for (j in ((i+1) : nrow(a))){
+ print(c(i,j))
+ }
+ }
[1] 1 2
[1] 1 3
[1] 2 3

Upvotes: 4

Related Questions