Outer function in R for upper triangular matrix

社会主义新天地 提交于 2019-12-22 10:58:32

问题


I have this code currently

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

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.


回答1:


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)))

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


来源:https://stackoverflow.com/questions/36158638/outer-function-in-r-for-upper-triangular-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!