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 <liu...@virginia.edu> wrote: > Hi there, > > I have two questions on matrix manipulation. For the first one, I want to > calculate the product of each column of a matrix (say A) with another vector > (say b). That is, if A has 5 columns (a1, a2, a3, a4, a5), I want to obtain > a matrix with columns (a1*b, a2*b, aA3*b, a4*b, a5*b). Can I do it directly, > without using "for" loop? > > For the second one, I have a matrix A of dimension 2 by n (say columns of > a1, a2, ..., an), another matrix B of dimension 2 by 2. I want to obtain the > vector with elements (t(a1) %*% B %*% a1, t(a2) %*% B %*% a2, ..., t(an) %*% > B %*% an). Can I do it without using "for" loop? > > Thanks a lot! > > Lei Liu > Associate Professor > Division of Biostatistics > Department of Public Health Sciences > University of Virginia School of Medicine > > http://people.virginia.edu/~ll9f/ > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > -- Joshua Wiley Ph.D. Student, Health Psychology Programmer Analyst II, ATS Statistical Consulting Group University of California, Los Angeles https://joshuawiley.com/ ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.