R中的上三角矩阵的外部函数 [英] Outer function in R for upper triangular matrix

查看:103
本文介绍了R中的上三角矩阵的外部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有此代码

s1=seq(0,10,length.out=3)
s2=seq(0,10,length.out=3)
d=outer(s1,s2,`-`)
I=outer(s1,s2,`==`)

但是我只想要d的上三角,所以我目前正在做

However I only want the upper triangular of d and I so I am currently doing

d=d[upper.tri(d,diag=T)]
I=I[upper.tri(I,diag=T)]

是否可以通过在外部函数中合并上三角矩阵来使此代码更快? 请注意,这是一个可重现的示例,但是我的代码更大,并且我需要尽可能减少运行时间.

Is there a way to make this code faster through incorporating the upper triangular matrix in the outer function? Note that this is a reproducible example, however my code is much bigger and I need to decrease the running time as much as possible.

推荐答案

outer在内部使用rep扩展其参数:

outer internally uses rep to stretch its arguments:

    Y <- rep(Y, rep.int(length(X), length(Y)))
    if (length(X)) 
        X <- rep(X, times = ceiling(length(Y)/length(X)))

您可以使用子集执行相同的操作,但是仅生成三角索引. sequence在这种情况下是有用的辅助功能:

You can do the same thing using subsetting, but instead generate only the triangular indices. sequence is a useful helper function in this case:

> i <- sequence(1:3)
> j <- rep(1:3, 1:3)
> d = s1[i] - s2[j]
> I = s1[i] == s2[j]
> d
[1]   0  -5   0 -10  -5   0
> I
[1]  TRUE FALSE  TRUE FALSE FALSE  TRUE

这篇关于R中的上三角矩阵的外部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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