-4

I am trying to create a matrix like this from a vector:

    vec =c(1, 2, 3)

    > A
          [,1] [,2] [,3] [,4] [,5]
    [1,]    1    1    0    0    0
    [2,]    1    2    1    0    0
    [3,]    1    3    2    1    0

and each time the length and value of vector vec is changing. How can I write a function to create this matrix?

Name is Nilay
  • 2,743
  • 4
  • 35
  • 77
Bensor Beny
  • 285
  • 2
  • 13
  • I'm lost - what is the desired relationship between the 3 values in the initial vector (vec) and the outcome matrix (A)? They seem to be in a descending lag from columns 2 to 5, but what is column 1 doing? – thelatemail May 31 '12 at 02:05
  • This question was reposted with more details at CrossValidated and migrated [here](http://stackoverflow.com/q/10851976/210673). – Aaron left Stack Overflow Jun 01 '12 at 16:38

2 Answers2

3

I'm a bit lost on the question, but this line

vec <- 1:3
embed(c(rep(0,length(vec)),vec),length(vec)+1)

...produces the last part of your desired result:

     [,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    2    1    0    0
[3,]    3    2    1    0

Which you can then bind to the first number of the vector.

cbind(vec[1],embed(c(rep(0,length(vec)),vec),length(vec)+1))

to give...

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    0    0
[2,]    1    2    1    0    0
[3,]    1    3    2    1    0
thelatemail
  • 91,185
  • 12
  • 128
  • 188
1

I think this might do it:

vec =c(1, 2, 3)

my.matrix <- matrix(0, nrow=length(vec), ncol=(max(vec)+2))
my.matrix


for(i in 1:length(vec)) {

     my.matrix[i,1] <- 1
     z <- seq(vec[i], 1, -1)
     my.matrix[i,2:(vec[i]+1)] <- z
}

my.matrix
Mark Miller
  • 12,483
  • 23
  • 78
  • 132