Skip to content
Prev 166543 / 398502 Next

Matrix: Problem with the code

On Fri, Jan 9, 2009 at 6:36 PM, <markleeds at verizon.net> wrote:
Bhargab gave us

     x<-c(23,67,2,87,9,63,8,2,35,6,91,41,22,3)

and said: "I want to have a matrix with p columns such that each
column will have the elements of  x^(column#)."

so, I think Charlotte's code was spot-on:

p <- 3
outer(x, 1:p, '^')
     [,1] [,2]   [,3]
 [1,]   23  529  12167
 [2,]   67 4489 300763
 [3,]    2    4      8
 [4,]   87 7569 658503
 [5,]    9   81    729
 [6,]   63 3969 250047
 [7,]    8   64    512
 [8,]    2    4      8
 [9,]   35 1225  42875
[10,]    6   36    216
[11,]   91 8281 753571
[12,]   41 1681  68921
[13,]   22  484  10648
[14,]    3    9     27


Here's another way -- a bit less elegant, but a gentle
introduction to thinking in vectors rather than elements:

 mat <- matrix(0,nrow=length(x), ncol=p)

 for(i in 1:p) mat[,i] <- x^i
 mat
     [,1] [,2]   [,3]
 [1,]   23  529  12167
 [2,]   67 4489 300763
 [3,]    2    4      8
 [4,]   87 7569 658503
 [5,]    9   81    729
 [6,]   63 3969 250047
 [7,]    8   64    512
 [8,]    2    4      8
 [9,]   35 1225  42875
[10,]    6   36    216
[11,]   91 8281 753571
[12,]   41 1681  68921
[13,]   22  484  10648
[14,]    3    9     27


best,

Kingsford Jones






So