[R] Product of certain rows in a matrix without loop

Gerrit Eichner Gerrit.Eichner at math.uni-giessen.de
Tue Sep 3 11:49:31 CEST 2013


Hello, Edouard,

taking logs of A's elements (so that * turns into +, so to say), using a 
left-multiplication with a certain band matrix of the package Matrix, and 
exponentiating the result again could provide a solution (see below).

> I know have the following problem:
> I have a matrix :
> A =
> 1  2  3
> 4  5  6
> 7  8  9
> 9  8  7
> 4  5  6
> 3  2  1
>
> And I would like to have :
> B =
> 1*4*7  2*5*8  3*6*9
> 4*7*9  5*8*8  6*9*7
> 7*9*4  8*8*5  9*7*6
> 9*4*3  8*5*2  7*6*1
>
> Here I took the product of 3 rows each time. And 3 needs to be a parameter.
>
> Is it possible to do so without any loop ?


Caveat: Not very carefully tested!

library( Matrix)

k <- 3
ones <- lapply( 1:k, function( j) rep( 1, nrow( A) - j + 1)))
leftmatrix <- bandSparse( n = nrow(A) - k + 1, m = nrow(A),
                           k = 0:(k-1), diagonals = ones)

exp( leftmatrix %*% log(A))

  Hth  --  Gerrit

---------------------------------------------------------------------
Dr. Gerrit Eichner                   Mathematical Institute, Room 212
gerrit.eichner at math.uni-giessen.de   Justus-Liebig-University Giessen
Tel: +49-(0)641-99-32104          Arndtstr. 2, 35392 Giessen, Germany
Fax: +49-(0)641-99-32109        http://www.uni-giessen.de/cms/eichner



More information about the R-help mailing list