将矩阵应用于函数 [英] Applying a matrix to a function
问题描述
尝试使用mapply将矩阵应用于函数
Trying to apply a matrix to a function, using mapply without success
我正在尝试求解一组针对不同参数的方程式.在函数集的一种更简单的形式中,我试图将一个函数传递给矩阵-常量-
I'm trying to solve a set of equations for different parameters. In a more simplistic form of the set of functions, I'm trying to pass a function to a matrix - constants -
a b c
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
并尝试求解方程式3*a + 2*b + 3*c
,并返回矩阵中每一行的答案.我已将原始功能更改为线性且更简单的功能-这就是为什么我更喜欢使用#mapply的原因,并且以前的说明对我没有帮助.
and trying to solve the the equation 3*a + 2*b + 3*c
and return the answer for each row in the matrix. I have changed the original function to a linear and more simple one - that is why I prefer using #mapply and that former explanations have not assisted me.
建立矩阵
my_vector <- 1:9
constants <- matrix(my_vector, 3, 3)
colnames(constants) <- c("a", "b", "c")
constants
目标功能
fun_abc <- function(a, b, c){
return(3 * a + 2 * b + 3 * c)
}
将常量应用于函数
applying constants to the function
mapply(fun_abc, 2, constants)
我不断收到错误消息(函数(a,b,c):缺少参数"c",没有默认值) 谁能发现问题?
I keep getting Error in (function (a, b, c) : argument "c" is missing, with no default Can anyone spot the problems?
推荐答案
您可以直接将值相乘并使用rowSums
来获取逐行求和
You can directly multiply values and take rowSums
to get row-wise sum
vals <- c(3, 2, 3)
rowSums(t(t(constants) * vals))
#[1] 32 40 48
我们使用转置,因为constants * vals
将在每列中乘以vals
,所以第一个转置是将vals
行式相乘,第二个转置是再次获取原始格式的矩阵.如果我们总是有一个方阵(nrow == ncol
),我们可以减少一个转置并使用colSums
来获得相同的值.
We use transpose since constants * vals
would multiply vals
in each column, so the first transpose is to multiply vals
row-wise and the second transpose is to get matrix in original format again. If we would always have a square matrix (nrow == ncol
), we can reduce one transpose and use colSums
instead to get the same value.
colSums(t(constants) * vals)
#[1] 32 40 48
如果我们想避免移调,我们也可以使用sweep
rowSums(sweep(constants, 2, vals, `*`))
这篇关于将矩阵应用于函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!