一次从矩阵中选择特定元素 [英] Selecting specific elements from a matrix all at once

查看:102
本文介绍了一次从矩阵中选择特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以一次从矩阵中选择一堆预先指定的元素?具体来说,假设我有以下矩阵:

Is there a way I can select a bunch of prespecified elements all at once from a matrix? Specifically, suppose I have the following matrix:

      58        59        60       62        63        64
58  0.000000  3.772139  6.367721 8.978718 12.197210 13.401126
59  3.772139  0.000000  3.755554 5.935946  9.592700 11.664533
60  6.367721  3.755554  0.000000 5.999409  9.324764 11.991269
62  8.978718  5.935946  5.999409 0.000000  3.810169  6.762802
63 12.197210  9.592700  9.324764 3.810169  0.000000  3.796884
64 13.401126 11.664533 11.991269 6.762802  3.796884  0.000000

我要选择单元格[1,2],[2,3],[3,4],[4,5],[5,6].我意识到我可以按索引引用它们,在这种情况下,我可以运行:

I want to select cells [1,2], [2,3], [3,4], [4,5], [5,6]. I realize that I can reference them by index, in this case I can run:

mymatrix[c(2,9,16,23,30)]

但是,从稍后阅读代码中并不能很清楚地看出这一点.有没有一种方法可以一次输入所有的实际(行,列)引用?

However, this is not very clear from reading the code later. Is there a way I can enter the actual (row, column) reference all at once?

推荐答案

可以使用2个列矩阵进行索引.将那些行号和列号转换为有效的R对象(而不是Matlab样式的表达式)后:

Indexing can be done with 2 column matrices. After converting those row and column numbers to a valid R object (rather than Matlab-style expressions):

> idxs <- gsub("\\]",")", gsub("\\[", "c(",  "[1,2], [2,3], [3,4], [4,5] ,[5,6]") )
# I edited the string value that idxs returned:
> midx <- rbind( c(1,2), c(2,3), c(3,4), c(4,5) ,c(5,6) )
> mat <-  matrix(scan(), nrow=6)  
1:  0.000000  3.772139  6.367721 8.978718 12.197210 13.401126
7:   3.772139  0.000000  3.755554 5.935946  9.592700 11.664533
13:   6.367721  3.755554  0.000000 5.999409  9.324764 11.991269
19:   8.978718  5.935946  5.999409 0.000000  3.810169  6.762802
25:  12.197210  9.592700  9.324764 3.810169  0.000000  3.796884
31:  13.401126 11.664533 11.991269 6.762802  3.796884  0.000000
37: 
Read 36 items
> mat[midx]
[1] 3.772139 3.755554 5.999409 3.810169 3.796884

如果您的目标是索引可以更广泛地实现的超对角线,则:

If your goal were to index the super-diagonal that could be accomplished more generally:

> mat[col(mat)==row(mat)+1]
[1] 3.772139 3.755554 5.999409 3.810169 3.796884

这篇关于一次从矩阵中选择特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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