Jio
Jio

Reputation: 608

"for" loop is not populating the matrix

I am calculating angles for each point with 'for' loop. But somehow the matrix is not populated as desirable. Only the first element in matrix is populated with calculated value.

w1 = c(-2.40154, -1.82937)
w2 = c(-2.079041, 101,0663)
xy = as.data.frame(coordinates(p))
angle  = function (w1, w2 , p, ...) {
   iterations = 2500
   a = sqrt ((w1[1]-w2[1])^2 + (w1[2]-w2[2])^2)
   tr <- matrix(ncol=1, nrow=iterations)
  for (i in 1:iterations) { 
    b[i] = sqrt ((p$coords.x1[i]-w1[1])^2 + (p$coords.x2[i]-w1[2])^2)
    c[i] = sqrt ((p$coords.x1[i]-w2[1])^2 + (p$coords.x2[i]-w2[2])^2)
    tr[i,] = (acos ((b[i]^2 + c[i]^2 - a^2)/ (2*b[i]*c[i]))*180)/pi
    print(tr)   
  }
  return(tr)
}
t = angle(w1,w2,xy)

tr is getting only the first value. Please correct the code.

Upvotes: 1

Views: 336

Answers (3)

Robert
Robert

Reputation: 5162

You did not tell us how is p defined. If you insist in using your code, iterations need to depend on rows of p.

w1 = c(-2.40154, -1.82937)
w2 = c(-2.079041, 101.0663)
p <- data.frame(coords.x1=c(4, 5,3), coords.x2=c(6, 7,5))
xy = as.data.frame(p)
angle1  = function (w1, w2 , p, ...) {
  iterations = nrow(p)
  b<-c<-vector()
  tr <- matrix(ncol=1, nrow=iterations)
  a = sqrt ((w1[1]-w2[1])^2 + (w1[2]-w2[2])^2)

  for (i in 1:iterations) { 
    b[i] = sqrt ((p$coords.x1[i]-w1[1])^2 + (p$coords.x2[i]-w1[2])^2)
    c[i] = sqrt ((p$coords.x1[i]-w2[1])^2 + (p$coords.x2[i]-w2[2])^2)    
    tr[i,] = (acos ((b[i]^2 + c[i]^2 - a^2)/ (2*b[i]*c[i]))*180)/pi
    #print(tr)
    }
  return(tr)
}
t = angle1(w1,w2,xy)
head(t)
         [,1]
[1,] 137.0707
[2,] 135.7236
[3,] 138.6321

Upvotes: 0

rcorty
rcorty

Reputation: 1200

You probably want to

return(tr)

after all passes through the for loop are done, not during the first pass through it.

EDIT: @josilber's answer is much better. This function is easily vectorizable as he shows.

Upvotes: 0

josliber
josliber

Reputation: 44340

Usually you don't want to loop through vectors performing one index at a time. You instead want to operate on the vectors as a whole. This will make your code both shorter and more efficient:

w1 = c(-2.40154, -1.82937)
w2 = c(-2.079041, 101,0663)
p <- data.frame(coords.x1=c(4, 5), coords.x2=c(6, 7))
angle <- function(w1, w2, p) {
  a <- sqrt ((w1[1]-w2[1])^2 + (w1[2]-w2[2])^2)
  b <- sqrt ((p$coords.x1-w1[1])^2 + (p$coords.x2-w1[2])^2)
  c <- sqrt ((p$coords.x1-w2[1])^2 + (p$coords.x2-w2[2])^2)
  return(matrix((acos ((b^2 + c^2 - a^2)/ (2*b*c))*180)/pi, ncol=1))
}
angle(w1, w2, p)
#          [,1]
# [1,] 137.0681
# [2,] 135.7206

Basically all I did was remove the for loop and the indexing by i and your code works as expected.

Upvotes: 3

Related Questions