提取矩阵的对角线(非对角线)元素 [英] Extract opposite-diagonal (not off-diagonal) elements of a matrix

查看:240
本文介绍了提取矩阵的对角线(非对角线)元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个太简单的问题,但是我找不到功能性的答案.我们如何提取R中任何方阵的对角线对角元素?在下面的示例中为:7, 2, 8.

May be this is too simple of a question but I couldn't find a functional answer. How can we extract the opposite diagonal elements of any square matrix in R? In the example below that would be: 7, 2, 8.

r <- matrix(c(1, 5, 8, 1:3, 7:9), 3)

推荐答案

一种方法可能是

r[(n<-nrow(r))^2-(1:n)*(n-1)]
# [1] 7 2 8

## microbenchmark (matrix(1:1e6,1000))
# Unit: microseconds
#         expr       min         lq        mean    median         uq      max neval
#  r[(n<-nr...    26.897    39.0075    65.36835    47.309    85.9345   316.97   100
#  diag(r[,... 18070.388 18905.3475 20237.09599 19956.615 20423.4695 27798.88   100
#  rev(r[ro... 14220.609 21206.7220 21238.59515 22036.275 22599.4490 33252.58   100

这篇关于提取矩阵的对角线(非对角线)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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