作为尝试对循环进行矢量化的一部分,我偶然发现了 R
中的 outer(X, Y, FUN = "*", ...)
函数。
我试图了解如何逐步重现以下结果:
set.seed(1)
b = rnorm(3, 0, 1)
t = rnorm(5)
使用 outer()
和 FUN
参数作为 -
我得到以下输出:
> outer(t, b, "-")
[,1] [,2] [,3]
[1,] -0.9134962 -1.7235934 -0.70432143
[2,] -0.3021132 -1.1122104 -0.09293842
[3,] 0.3317334 -0.4783638 0.54090817
[4,] 0.6206866 -0.1894105 0.82986144
[5,] 3.0311072 2.2210101 3.24028200
使用 outer()
和 FUN
参数作为 *
我得到:
> outer(t, b, "*")
[,1] [,2] [,3]
[1,] 0.964707572 -0.282801545 1.286826317
[2,] 0.581704357 -0.170525137 0.775937183
[3,] 0.184628747 -0.054123443 0.246276838
[4,] 0.003612867 -0.001059103 0.004819215
[5,] -1.506404279 0.441598542 -2.009397175
我可以通过 t %*% t(b)
重现 outer(t, b, "*")
,但我想不通如何为 outer(t, b, "-")
做这件事。
我对矩阵代数的了解相当有限,但我想试一试。你能帮帮我吗:
- 重现
FUN
设置为-
的情况
- 阐明
FUN
的实际作用?
谢谢。
最佳答案
问题是从 stats.stackexchange
迁移而来的,原始答案包括数学方程式。您可以在下面找到原始文本,以及保留格式的图片。
图片(保留格式)
原文
The outer product of two vectors $x,y$ (which do not need to have the same dimension) is often written $x y^T$ or, with more details, $$ \begin{pmatrix} x_1 \ x_2 \ \vdots \ x_n \end{pmatrix} \cdot
\begin{pmatrix} y_1 & y_2 & \dots & y_m \end{pmatrix} $$ and the result is the $n \times m $ matrix $$ \begin{pmatrix} x_1 y_1 & x_1 y_2 & \dots x_1 y_m \ x_2 y_1 & x_2 y_2 & \dots x_2 y_m \ \vdots \ x_n y_1 & x_n y_2 & \dots & x_n y_m \end{pmatrix} $$ So, you can see, the result is an $n\times m$ matrix where element $i,j$ is given by $x_i \cdot y_j$. So this is outer product where the FUN is ordinary multiplication. In general, the result is the same, always an $n \times m$-matrix, where ordinary multiplication is replaced with an arbitrary two-place function $\text{FUN}(x,y)$, so if that function is ordinary minus, $-$ then the $i,j$ element becomes $x_i - y_j$, if FUN is power, $\text{FUN}(x,y) = x^y$ then the $i,j$ element becomes $x_i^{y_j}$, and so on.This could even be used with non-numerical functions.
关于r - 外积如何在 R 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42513846/