在R中创建一个递增的数字同心环矩阵 [英] Creating a matrix of increasing concentric rings of numbers in R

查看:68
本文介绍了在R中创建一个递增的数字同心环矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在R中编写一个函数,该函数创建一个递增的同心数字环矩阵.该函数的参数是多个层.例如,如果x = 3,则矩阵将如下所示:

I need to write a function in R that creates a matrix of increasing concentric rings of numbers. This function's argument is a number of layers. For example, if x = 3, matrix will look like following:

1 1 1 1 1  
1 2 2 2 1  
1 2 3 2 1  
1 2 2 2 1  
1 1 1 1 1

我不知道该怎么做.我真的很感谢任何建议.

I have no idea how to do it. I would really appreciate any suggestions.

推荐答案

1)试试:

x <- 3 # input

n <- 2*x-1
m <- diag(n)
x - pmax(abs(row(m) - x), abs(col(m) - x))

给予:

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

2)第二种方法是:

x <- 3 # input

n <- 2*x-1
mid <- pmin(1:n, n:1)  # middle row/column
outer(mid, mid, pmin)

得到与以前相同的结果.

giving the same result as before.

3)与前两种方法有一些相似之处的另一种方法是:

3) yet another approach having some similarities to the prior two approaches is:

x <- 3 # input

n <- 2*x-1
Dist <- abs(seq_len(n) - x)
x - outer(Dist, Dist, pmax)

注意:上面给出了问题中显示的示例矩阵,但是问题的主题是指环应该在增加,这可能意味着从中心到外部增加,如果那是想要然后尝试使用mmidDist像以前一样的方法:

Note: The above gives the sample matrix shown in the question but the subject of the question says the rings should be increasing which may mean increasing from the center to the outside so if that is what is wanted then try this where m, mid and Dist are as before:

pmax(abs(row(m) - x), abs(col(m) - x)) + 1

x - outer(mid, mid, pmin) + 1

outer(Dist, Dist, pmax) + 1

其中任何一个都可以给

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

这篇关于在R中创建一个递增的数字同心环矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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