[R] 2 questions on matrix manipulation in R

David Winsemius dwinsemius at comcast.net
Mon Aug 8 07:57:23 CEST 2011


On Aug 8, 2011, at 12:18 AM, Lei Liu 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?

b*A  # arithmetic operations on matrices are column-wise and argument  
recycling accomplishes the "loopless looping".


>
> 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?

Perhaps:

B <- matrix(1:4, 2)
A <- matrix(1:10, 2)

apply(A, 2, function(x) x %*% B %*% x)
[1]  27 133 319 585 931

(Also not that this is only more compact than a loop. It should not be  
expected to be more efficient since it is really a loop "underneath  
the hood".)

Also noticed that this would yield the same result and it well could  
be faster, despite the extraneous results that get discarded:

diag(  crossprod( A, crossprod(B, A)) )


But other interpretations seem possible. Maybe next time you can heed  
the admonitions in the Posting Guide and offer a reproducible example  
and say what you think the answer should be?

-- 


>
> 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 at 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list