创建有限制的对角矩阵

时间:2019-06-22 15:37:26

标签: r

@Override
public boolean onMapClick(@NonNull LatLng point) {

 // Get the clicked point coordinates
 PointF screenPoint = mapboxMap.getProjection().toScreenLocation(point);

 // Query the source layer in that location
 List<Feature> features = mapboxMap.queryRenderedFeatures(screenPoint, "MY_SOURCE_LAYER_ID");

 if (!features.isEmpty()) {

  // get the first feature in the list
  Feature feature = features.get(0);

  // do stuff...
 }

 return true;
}

我必须生成上面的矩阵,但是我有一些限制。 我不允许使用任何内置函数,例如matrix(),cbind(),rbind()(length()除外)或任何循环。我必须使用apply函数解决这个问题。

该函数只有一个参数(比方说7)可以在上面生成此矩阵。

我解决此问题的方法是,我创建一个起始向量,然后使用sapply函数将此起始向量转换为矩阵。然后,我要对该矩阵进行操作以获得所需的输出。

1 个答案:

答案 0 :(得分:0)

您正确地确定可以使用sapply解决问题。请查看下面的代码(快速且肮脏):

n <- 7

gen_xs <- function(x) c(0, seq(1, x, 2))

move0 <- function(x, pos) {
  if (pos == 0)
    return(x)
  if (pos == length(x) - 1)
    return (c(x[-1], 0))
  xt <- x[x != 0]
  c(xt[1:pos], 0, xt[(pos + 1):length(xt)] )
}

t(sapply(0:((n + 1) / 2), function(x) move0(gen_xs(n), x)))

输出:

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    3    5    7
[2,]    1    0    3    5    7
[3,]    1    3    0    5    7
[4,]    1    3    5    0    7
[5,]    1    3    5    7    0