将向量中的每个元素本身相乘以创建矩阵
问题描述:
我试图将向量中的每个元素自身相乘,以使其产生一个围绕对角线对称的矩阵.例如,给定此向量:
I'm trying to multiply each element in a vector by itself such that it produces a matrix that is symmetric about the diagonal. For example, given this vector::
x <- 1:3
我想创建这个:
1 2 3
2 4 6
3 6 9
即:
x[1]*x[1] x[2]*x[1] x[3]*x[1]
x[1]*x[2] x[2]*x[2] x[3]*x[2]
x[1]*x[3] x[2]*x[3] x[3]*x[3]
任何帮助将不胜感激.谢谢.
Any help would be greatly appreciated. Thanks.
答
像这样:
x %o% x
这是
outer(x, x)
您也可以
tcrossprod(x)