14
> a<-matrix(c(1:9),3,3)
> a
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> a[3,]*a[,3]  # I expect 1x1 matrix as result of this.
[1] 21 48 81
> class(a)
[1] "matrix"
> class(a[3,])
[1] "integer"

In R, 1-dimensional matrix is changed to a vector. Can I avoid this? I would like to keep 1-D matrix as a matrix. Actually, I need to throw many kind of matrix to RcppArmadillo, even zero-D matrix. Changing matrix to vector by itself is my problem.

Jona
  • 629
  • 1
  • 6
  • 16
  • `class(a[3,])` only tells you the storage mode. You probably should be using str() since it would tell you the `length`. – IRTFM Mar 30 '12 at 19:40

2 Answers2

19

This is an R FAQ. You need to do a[3,,drop = FALSE].

joran
  • 169,992
  • 32
  • 429
  • 468
9

You're confusing element-by-element multiplication and matrix multiplication (see ?"*"). You want %*%:

> a[3,]%*%a[,3]
     [,1]
[1,]  150
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418