n = 5; p = 2; matrix(1:(n*p),n,p) # n rows, p col
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
n = 5; p = 2
X = matrix(ncol = p, nrow = n)
for (i in 1:p) {
X[, i] = 1:n
}
X
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4
[5,] 5 5
When matrix
turns a vector into a matrix, the
default order is to fill the matrix by columns.
(All vectors, unless specifically modified, are considered column vectors, even
if they print out as rows.)
w = c(1,2,3,4,3,2) # 'c' for column vector
X = as.matrix(w)
X
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 3
[6,] 2
t(X) # transpose is a row vector
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 3 2
t(X) %*% X # matrix multiplication
[,1]
[1,] 43
X %*% t(X)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 3 2
[2,] 2 4 6 8 6 4
[3,] 3 6 9 12 9 6
[4,] 4 8 12 16 12 8
[5,] 3 6 9 12 9 6
[6,] 2 4 6 8 6 4
X*t(X)
Error in X * t(X) : non-conformable arrays
t(w)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 3 2
t(w)%*%w
[,1]
[1,] 43