Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:如何将值矩阵转化为函数_R - Fatal编程技术网

R:如何将值矩阵转化为函数

R:如何将值矩阵转化为函数,r,R,我有一个nxm值矩阵。在这个玩具示例中,假设n=m=3 mymat <- matrix(c(16, -15, -2, 15, 13, 16, 0, 0, 0.42), nrow = 3, ncol = 3) > mymat [,1] [,2] [,3] [1,] 16 15 0.00 [2,] -15 13 0.00 [3,] -2 16 0.42 然而,如果mymat的维度增加,那么构造这个函数是非常繁琐的。有没有更有效的编码方法?如果在x的末尾添

我有一个
nxm
值矩阵。在这个玩具示例中,假设
n=m=3

mymat <- matrix(c(16, -15, -2, 15, 13, 16, 0, 0, 0.42), nrow = 3, ncol = 3)
> mymat
     [,1] [,2] [,3]
[1,]   16   15 0.00
[2,]  -15   13 0.00
[3,]   -2   16 0.42

然而,如果
mymat
的维度增加,那么构造这个函数是非常繁琐的。有没有更有效的编码方法?

如果在
x
的末尾添加
1
,您所描述的是矩阵乘法

以下是您的功能:

foo = function(x, mat) {
  c(mat %*% c(x, 1))
}
演示:

all(myfun(1:2) == foo(1:2, mymat))
# [1] TRUE

all(myfun(3:4) == foo(3:4, mymat))
# [1] TRUE

如果将
1
添加到
x
的末尾,则您描述的是矩阵乘法

以下是您的功能:

foo = function(x, mat) {
  c(mat %*% c(x, 1))
}
演示:

all(myfun(1:2) == foo(1:2, mymat))
# [1] TRUE

all(myfun(3:4) == foo(3:4, mymat))
# [1] TRUE