# [R] matrix diagonal calculations follow up

Griffith Feeney gfeeney at gfeeney.com
Mon May 28 22:48:37 CEST 2001

```Thanks to Alex Stephenson and Martin Henry H. Stevens for replies. The code
below uses a loop but is quick enough for my purposes, which involve small
numbers of calculations with matrices with numbers of cells in the low 5
figures.

On Sat, 19 May 2001, Griffith Feeney wrote:
> Given an nxm matrix A I want to compute the nxm matrix B whose ij-th
> element is the sum of the elements of A lying on the diagonal that ends
> with element ij, i.e.,
>
>      b_ij = a_ij + a_(i-1)(j-1) + a_(i-2)(j-2) + ...
>
> In APL (which I no longer use), I would use the 'rotate' operator to derive
> an array whose columns are diagonals of the given array and then cumulate
> down columns. Is there a similar operator in R, or is there
another/better way?

> cumprod.diagonals
function (matrix.in)
{
dump("cumprod.diagonals", "cumprod.diagonals.R")
n <- dim(matrix.in)[1]
m <- dim(matrix.in)[2]
matrix.out <- matrix(0, nrow=n, ncol=m)
for (j in 1:m) {
cols <- j:min(m, n + j - 1)
rows <- 1:length(cols)
index.matrix <- matrix(c(rows, cols), ncol = 2)
matrix.out[index.matrix] <- cumprod(matrix.in[index.matrix])
}
for (i in 1:n) {
rows <- i:min(n, m + i - 1)
cols <- 1:length(rows)
index.matrix <- matrix(c(rows, cols), ncol = 2)
matrix.out[index.matrix] <- cumprod(matrix.in[index.matrix])
}
matrix.out
}

(I've switched from sum to product. Repeated calculation for the diagonal
is intentional, as I may want to comment out one or the other loops.)

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```