向量到元素之间的差异矩阵 [英] Vector to Matrix of Differences between elements

查看:96
本文介绍了向量到元素之间的差异矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个向量:

vec <-1:5

创建矩阵的一种有效方法是,将矢量分量之间的差显示在一个矩阵(如果需要的话)中.我显然可以使用两个for循环来执行此操作,但是我需要使用更大的数据集来执行此操作.我正在尝试制作这个矩阵的术语,但是我没有运气.结果就是这样.

What is an efficient way to create a matrix where the difference between the vector components are displayed in a matrix, a difference matrix, if you will. I could obviously do this with two for loops, but I need to do this with a much larger set of data. There is likely a term for this matrix I am trying to make, but I am not having any luck finding it. Here is what the result would look like.

m<-matrix(c(NA), ncol=5, nrow=5, byrow=TRUE)
rownames(m)<-1:5;colnames(m)<-1:5
for(i in 1:5){for(j in 1:5){m[i,j]<-(as.numeric(rownames(m)[i])-as.numeric(rownames(m)[j]))}}
m

感谢您的帮助!

推荐答案

通常使用outer完成.

outer(1:5, 1:5, '-')

有关详细信息,请参见?outer.

See ?outer for details.

这篇关于向量到元素之间的差异矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆