函数返回R中的二次矩阵 [英] Function returns quadratic matrix in R

查看:103
本文介绍了函数返回R中的二次矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数,该函数返回一个二次矩阵,其每个元素是行号或列号的平方,具体取决于哪个更大 这是我的代码,但是到目前为止还行不通. 有人可以帮忙吗???

I created a function that returns a quadratic matrix whose each element is the square of either the row or the column number depending on which is greater here's my code, but it doesn't work so far. Anybody can help????

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并在最后返回正确的对象即可.

You were almost there. you just had to specify n and return the right object at the end.

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

这篇关于函数返回R中的二次矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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