Skip to content
Prev 267932 / 398502 Next

2 questions on matrix manipulation in R

Hi Lei,

Here are some examples.  Look at the documentation for ?"%*%" ?"%o%"
and ?"[" with the drop = FALSE argument (in case you ever do select
just one column/row of a matrix).

## your first A matrix
(A <- matrix(1:55, ncol = 5))

## you were rather unclear what
## your b vectors dimensions were
## here are some possibilities
(b1 <- 5)
(b2 <- 1:11)
(b3 <- 1:5)

## you were also unclear whether
## what sort of multiplication was going on
## here are some possibilities
A * b1
A * b2
## equivalenet to each column of A %*% b3
A %o% b3

## your second A matrix and B matrix
(A2 <- matrix(1:30, nrow = 2))
(B <- matrix(1:4, 2))

## obviously does a little more work than needed
## but for most cases, still probably easier than a loop
diag(t(A2) %*% B %*% A2)

Cheers,

Josh

BTW, these strike me as more linear algebra questions than really R
questions.  Even without the builtin recycling etc. one could
construct the necessary matrices to do it without loops fairly easily.
On Sun, Aug 7, 2011 at 9:18 PM, Lei Liu <liulei at virginia.edu> wrote: