“用于"循环未填充矩阵 [英] "for" loop is not populating the matrix

查看:52
本文介绍了“用于"循环未填充矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用"for"循环计算每个点的角度.但是不知何故矩阵没有被填充.仅矩阵中的第一个元素填充了计算值.

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 仅获得第一个值.请更正代码.

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

推荐答案

通常,您不想遍历一次执行一个索引的向量.相反,您想对向量进行整体操作.这将使您的代码更短,更高效:

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

基本上,我所做的只是删除了循环并通过 i 建立索引,您的代码按预期运行.

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

这篇关于“用于"循环未填充矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆