Skip to content
Prev 167508 / 398502 Next

Using apply to generate matrix from rows?

Dear all,


I have a simple question which I unfortunately do not seem to be able
to solve myself. I have a (NxK) matrix and want to generate a new
matrix by multiplying each row with itself such that the new matrix
has dimension ((N*K)xK) (or better, generate an array with dimension
(K,K,N)). I tried apply, but that did not work. Any suggestions? 

Thanks! 


	Stephan



## Here is a simple example: 

u <- matrix(c(1,2,3,4,5,6,7,8,9,10),nrow=2)

## What I want to obtain 

u[1,]%*%t(u[1,])
u[2,]%*%t(u[2,])

## stacked together --> 10x5 matrix


## This does not work 

sq <- function(x)x%*%t(x)
apply(u,1,function(y)sq(y))