如何在R中给定维度的矩阵中随机生成+1
和-1
?
例如:对于大小为3 * 5的矩阵,矩阵可以是:
-1 -1 1 1 -1
1 -1 1 1 1
-1 -1 -1 -1 1
答案 0 :(得分:2)
尝试
nr = 3 # number of rows
nc = 5 # number of columns
M = matrix(sample(c(-1, 1), nr * nc, replace = TRUE), nrow = nr)
print(M)
[,1] [,2] [,3] [,4] [,5]
[1,] -1 -1 -1 1 -1
[2,] 1 1 1 -1 -1
[3,] 1 1 1 1 1