如何在正方形的特定部分生成点

问题描述 投票:0回答:4

[假设我有一个size 10x10的平方,然后将这个平方分为相等的部分,例如,分成4个相等的部分(可以是其他数字,例如2、8、16,...)。之后,在循环中,我想随机选择4个部分之一,并在此正方形中生成一个点。在这里,我将选择第二个正方形。

min.x = 0
max.x=10
min.y=0
max.y=10
xd = xMax-xMin 
yd = yMax-yMin 
#generating randomly coordinates at the second square
set.seed(1)
xx_1 = 5*runif(1) + 5; yy_1 = 5*runif(1) + 0
#ploting the big square and the point in the second square just to ilustrate

enter image description here

对于此示例,如果我将手动进行操作,则可以对以下四个正方形中的每个正方形使用以下函数:

    xx_1 = 5*runif(1)+0; yy_1 = 5*runif(1)+0
    xx_2 = 5*runif(1)+5; yy_2 = 5*runif(1)+0
    xx_3 = 5*runif(1)+0; yy_3 = 5*runif(1)+5
    xx_4 = 5*runif(1)+5; yy_4 = 5*runif(1)+5

有关如何自动生成特定正方形中的点的任何提示?

r process poisson
4个回答
1
投票

这里有一个小功能可以满足您的要求。您告诉它正方形的大小(即一侧的长度),要切成的块数(显然应该是一个正方形数),以及要在其中随机采样的块数(从左到右)从右到下,如您的示例所示。

square_sample <- function(size = 10, pieces = 4, n = 1)
{
  vals <- seq(0, size, length.out = sqrt(pieces) + 1)
  x_min <- ((n - 1) %% sqrt(pieces)) * size/sqrt(pieces)
  y_min <- ((n - 1) %/% sqrt(pieces)) * size/sqrt(pieces)
  c(x = runif(1, x_min, x_min + size/sqrt(pieces)), 
    y = runif(1, y_min, y_min + size/sqrt(pieces)))
}

在您的示例上进行测试:我们应该得到一个x值在5到10之间,而y值在0到5之间的点:

square_sample(size = 10, pieces = 4, n = 2)
#>        x        y 
#> 5.968655 3.254514 

或选择将150 * 150正方形的中间正方形切成9块。在这里,我们期望x和y都在50到100之间:

square_sample(size = 150, pieces = 9, n = 5)
#>        x        y 
#> 78.47472 97.32562 

1
投票

您可以使用三个参数编写函数:

  • 您想“向右”移动的方块数(在您的图片中:1和3的方块为0,2和4的方块为2)
  • 您要增加的平方数(0表示1&2的正方形,2表示3&4的正方形)

  • 正方形大小的长度

使用这些参数,您应该能够重新修改代码,将+ 0 / + 5替换为参数*正方形的宽度

  xx_1 = square_length*runif(1)+right_param * square_length
  yy_1 = square_length*runif(1)+upwards_param * square_length

1
投票
x.min = 0
x.max=10
y.min=0
y.max=10

num.random = 100

possible.squares = c(1,2,4,8,16)

squares = sample(possible.squares, 1)

x.length = x.max/squares
y.length = y.max/squares

x.coord = seq(from=x.min, to=x.max, by = x.length)
y.coord = seq(from=y.min, to=y.max, by = y.length)


set.seed(1)

loop {
  n = #<which ever square you want>
  x.rand = runif (1, min = x.coord[n-1], max = x.coord[n])
  y.rand = runif (1, min = y.coord[n-1], max = y.coord[n])
  #(x,y) is your coordinate for the random number in the nth square
}

有帮助吗?


1
投票

您可以使用复数矢量的绝对实数部分,此代码将生成您想要的任意数量的点。

Npoints = 4        # any multiple of 4 will generate equal number of points in each quarterion

x = Re(1i**(1:Npoints)) %>% abs 
y = Re(1i**(0:(Npoints-1))) %>% abs

randoms = lapply(1:(2*Npoints),function(x){
  5*runif(1)
})%>% unlist

coor.mat =cbind(x + randoms[1:Npoints],
                y + randoms[(Npoints +1) : (2*Npoints)])

现在coor.mat应该是2列矩阵,其中col1是x,col2是y,行数是要生成的点数。

编辑:小更正

© www.soinside.com 2019 - 2024. All rights reserved.