Bensor Beny
Bensor Beny

Reputation: 285

Efficient way to create matrix in R

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?

Upvotes: 3

Views: 2104

Answers (2)

Macro
Macro

Reputation: 1510

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

Upvotes: 5

ALiX
ALiX

Reputation: 1031

I don't know about efficiency, but here are two solutions without using for loops:

n <- length(vec)    
A <- replicate(n+1, vec) - cbind(0, t(replicate(n, vec)))
A[upper.tri(A)] <- 0

This one is longer but creates only one matrix

n <- length(vec)
A <- replicate(n, vec)
A <- A - t(A)
A <- cbind(vec, A)
A[upper.tri(A)] <- 0

Upvotes: 7

Related Questions