Search code examples
rmatrixmatrix-multiplication

How might I raise all elements in the ith column of a matrix to the power of i?


I am currently trying to create an nxm matrix of accumulation factors based on a selection of n interest rates of m time periods. So, for example, the first row gives me the evolution of a single unit accumulating at an interest rate of r1, the second row the evolution at an interest rate of r2, and so on. This should give me a matrix that looks something like

1+r1    (1+r1)^2    (1+r1)^3    ...
1+r2    (1+r2)^2    (1+r2)^3    ...
1+r3    (1+r3)^2    (1+r3)^3    ...
 .
 .
 .

To do this, I have created a matrix of the form

1+r1    1+r1    1+r1    ...
1+r2    1+r2    1+r2    ...
1+r3    1+r3    1+r3    ...
 .
 .
 .

(with constant rows) and was hoping to raise every element in the ith row to the power of i (without using a loop). How might this be done?


Solution

  • One option is to loop over the sequence of columns, extract the matrix column and raise it to the power of the index

    sapply(seq_len(ncol(m1)), function(i) (1 + m1[,i])^i)
    #      [,1] [,2] [,3]   [,4]     [,5]
    #[1,]    2   49 1728  83521  5153632
    #[2,]    3   64 2197 104976  6436343
    #[3,]    4   81 2744 130321  7962624
    #[4,]    5  100 3375 160000  9765625
    #[5,]    6  121 4096 194481 11881376
    

    Or without using a loop, make use of the col index which will return the same dimension as the original matrix and then do the power on the same dimension matrix

    (m1 + 1)^col(m1)
    #    [,1] [,2] [,3]   [,4]     [,5]
    #[1,]    2   49 1728  83521  5153632
    #[2,]    3   64 2197 104976  6436343
    #[3,]    4   81 2744 130321  7962624
    #[4,]    5  100 3375 160000  9765625
    #[5,]    6  121 4096 194481 11881376
    

    Or another option is rep

    (m1 + 1)^(rep(seq_len(ncol(m1)), each = nrow(m1)))
    

    data

    m1 <- matrix(1:25, 5, 5)