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

Gerrit Eichner Gerrit.Eichner at math.uni-giessen.de
Tue Sep 3 12:03:32 CEST 2013


> Thank you very much for your answer. Unfortunately, I cannot use any 
> package...
Er, ... this is quite unusual! (Is this is homework?)

> Do you have a solution ?
Well, take a look at the resulting bandmatrix leftmatrix. Yould can 
certainly build it yourself "by hand" somehow. I used the Matrix package 
just for convenience.

  Regards -- Gerrit

> Thank you in advance
>
>
> Edouard Hardy
>
>
> On Tue, Sep 3, 2013 at 11:49 AM, Gerrit Eichner <
> Gerrit.Eichner at math.uni-giessen.de> wrote:
>
>> 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



More information about the R-help mailing list