函数返回R中的二次矩阵



我创建了一个函数,该函数返回一个二次矩阵,其每个元素都是行数或列数的平方,取决于哪个更大这是我的代码,但到目前为止还不起作用。有人能帮忙吗????

matrix_a = function(A) {A = matrix(data = 0, nrow = n, ncol = n) for (i in 1:n) {
for (j in 1:n) {
if (i>=j) {A[i,j] = (i^2)} 
if (i<j) {A[i,j] = (j^2)}
}} return(matrix_a)}

您可以进行

n <- 3
mat <- matrix(nrow = n, ncol = n)
pmax(row(mat), col(mat)) ^ 2
#     [,1] [,2] [,3]
#[1,]    1    4    9
#[2,]    4    4    9
#[3,]    9    9    9

将其转换为功能

f1 = function(n = 2) {
mat <- matrix(nrow = n, ncol = n)
pmax(row(mat), col(mat)) ^ 2
}
f1()
#     [,1] [,2]
#[1,]    1    4
#[2,]    4    4

使用outer的第二个选项

f2 <- function(n = 3) {
tmp <- (1:n)^2
outer(tmp, tmp, pmax)
}

你差不多到了。您只需要指定n并在末尾返回正确的对象。

matrix_a = function(n) {
A = matrix(data = 0, nrow = n, ncol = n) 
for (i in 1:n) {
for (j in 1:n) {
if (i>=j) {A[i,j] = (i^2)} 
if (i<j) {A[i,j] = (j^2)}
}
} 
A
}
matrix_a(3)
#      [,1] [,2] [,3]
# [1,]    1    4    9
# [2,]    4    4    9
# [3,]    9    9    9

最新更新