Efficient way to create matrix in R

matrix, r

Solution

I think this will do what you want:

f = function(vec)
{
   n = length(vec)  
   M = matrix(0,n,n+1)
   M[,1] = vec
   for(i in 1:n) M[,i+1] = c(rep(0,i),vec[-c(1:i)]-vec[i])
   return(M)
}

vec = c(2,5,9)
f(vec)
     [,1] [,2] [,3] [,4]
[1,]    2    0    0    0
[2,]    5    3    0    0
[3,]    9    7    4    0

Problem

I am trying to create a matrix like this from a vector: ``` vec= c(2, 5, 9) > A [,1] [,2] [,3] [,4] [1,] 2 0 0 0 [2,] 5 3 0 0 [3,] 9 7 4 0 ``` Actually always the first column is the vector element, the second column start with 0 and then the (5-2 = 3) and then the thirld element of second column is (9-2 = 7). Then the third column start with 0 and then 0 and (9-5 = 4) and the last column is always zero. May be the length of vec changes to any number for example 4, 5,... .How can I write an efficient function or code to create this matrix?

Original source

Related problems