Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diagonal of a 3D array

How can one extract the "diagonal" from three-dimensional array in R? For a matrix (2D array) one can use the diag(...) function. In a similar way, given an N x N x M array, a natural operation is to convert it into an N x M matrix by taking the diagonal from each N x N slice and returning it as a matrix.

It's easy to do this using a loop, but that is not idiomatic R and is slow. Another possibility is to use slightly complex indexing (see my own answer to this question) but it is a bit hard to read. What other alternatives are there? Is there a standard R way to do this?

like image 873
banbh Avatar asked Dec 12 '25 08:12

banbh


2 Answers

Create an array and fill it by some values:

> a=array(0,c(10,10,5))
> for (i in 1:10) for (j in 1:10) for (k in 1:5) a[i,j,k]=100*i+10*j+k-111

Run the apply function:

> apply(a,3,diag)
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    1    2    3    4
 [2,]  110  111  112  113  114
 [3,]  220  221  222  223  224
 [4,]  330  331  332  333  334
 [5,]  440  441  442  443  444
 [6,]  550  551  552  553  554
 [7,]  660  661  662  663  664
 [8,]  770  771  772  773  774
 [9,]  880  881  882  883  884
[10,]  990  991  992  993  994
like image 60
user31264 Avatar answered Dec 15 '25 20:12

user31264


Various diagonals:

A = array(1:12, c(2, 2, 3))

apply(A, 1, diag)
#     [,1] [,2]
#[1,]    1    2
#[2,]    7    8
apply(A, 2, diag)
#     [,1] [,2]
#[1,]    1    3
#[2,]    6    8
apply(A, 3, diag)
#     [,1] [,2] [,3]
#[1,]    1    5    9
#[2,]    4    8   12
like image 35
eddi Avatar answered Dec 15 '25 22:12

eddi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!