本文介绍了R:外层,矩阵和向量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更好地理解外部函数如何工作以及如何对函数进行向量化.以下是我要执行的操作的最小示例:我有一组数字2,3,4.对于(a,b)的每个组合,创建对角线矩阵,对角线矩阵上的a a b b b,然后对其进行处理,例如计算其行列式(仅用于演示目的).计算结果应以3 x 3矩阵的形式写成,每种组合用一个字段表示.

I'd like to understand better how outer works and how to vectorize functions. Below is a minimal example for what I am trying to do:I have a set of numbers 2,3,4. for each combination (a,b) of create a diagonal matrix with a a b b b on the diagonal, and then do something with it, e.g. calculating its determinant (this is just for demonstration purposes). The results of the calculation should be written in a 3 by 3 matrix, one field for each combination.

下面的代码不起作用-显然,outer(或my.func)不理解我不希望应用整个lambdas向量-您可以看到是这种情况取消注释包含的print命令时.

The code below isn't working - apparently, outer (or my.func) doesn't understand that I don't want the whole lambdas vector to be applied - you can see that this is the case when you uncomment the print command included.

lambdas <- c(1:2)
my.func <- function(lambda1,lambda2){
# print(diag(c(rep(lambda1,2),rep(lambda2,2))))
 det(diag(c(rep(lambda1,2),rep(lambda2,2))))
}
det.summary <- outer(lambdas,lambdas, FUN="my.func")

我该如何修改我的函数或外部调用,使事情表现得像我想要的那样?

How do I need to modify my function or the call of outer so things behave like I'd like to?

我想我需要以某种方式对函数进行矢量化处理,但我不知道该怎么做,以及以何种方式对外部调用进行不同的处理.

I guess I need to vectorize my function somehow, but I don't know how, and in which way the outer call would be processed differently.

我更改了矩阵的大小,以减少混乱.我想用以下对角线生成4个对角线4 x 4矩阵.在括号中,对应的参数lambda1, lambda2:

I've changed size of the matrices to make it a bit less messy. I'd like to generate 4 diagonal 4 by 4 matrices, with the following diagonals; in are brackets the corresponding parameters lambda1, lambda2:

1 1 1 1 (1,1)1 1 2 2 (1,2)2 2 1 1 (2,1)2 2 2 2 (2,2).

然后,我要计算其行列式(此处是任意选择),并将结果放入矩阵中,其第一列对应于lambda1=1,第二列对应于lambda1=2,行对应于选择lambda2. det.summary应该是2乘以矩阵,并具有以下值:

Then, I want to calculate their determinants (which is an arbitrary choice here) and put the results into a matrix, whose first column corresponds to lambda1=1, the second to lambda1=2, and the rows correspond to the choice of lambda2. det.summary should be a 2 by to matrix with the following values:

1 4
4 16

因为它们是上面列出的对角矩阵的决定因素.

as these are the determinants of the diagonal matrices listed above.

推荐答案

您知道吗,有一个Vectorize函数(大写的"V")!

What do you know, there is a Vectorize function (capital "V")!

outer(lambdas,lambdas, Vectorize(my.func))
#      [,1] [,2]
# [1,]    1    4
# [2,]    4   16

您已经弄清楚(并且花了我一段时间才能弄清)outer要求将函数向量化.在某些方面,与*pply函数相反,它通过依次向操作员/函数提供每个值来有效地向量化操作.但这很容易解决,如上所示.

As you figured out (and as it took me a while to figure out) outer requires the function to be vectorized. In some ways, it is the opposite of the *pply functions which effectively vectorize an operation by feeding the operator/function each value in turn. But this is easily dealt with, as shown above.

这篇关于R:外层,矩阵和向量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 15:35