[R] Looping matrix multiplication

R. Michael Weylandt michael.weylandt at gmail.com
Thu Nov 8 19:38:34 CET 2012


On Thu, Nov 8, 2012 at 6:16 PM, Nordlund, Dan (DSHS/RDA)
<NordlDJ at dshs.wa.gov> wrote:
>
>> -----Original Message-----
>> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
>> project.org] On Behalf Of wilkesma
>> Sent: Thursday, November 08, 2012 5:49 AM
>> To: r-help at r-project.org
>> Subject: [R] Looping matrix multiplication
>>
>> I am dealing with a number of time-series consisting of 2250 samples of
>> flow
>> velocity in 2D (Vx, Vy).
>>
>> For each time-series I have determined the resultant vector angle (d)
>> and
>> magnitude (Vres) based on the ensemble means of Vx and Vy and now want
>> to
>> rotate each point in the time-series by d so that mean(Vx)=Vres and
>> mean(Vy)=0.
>>
>> Here is the code I have written to perform the rotation for a single
>> time-step:
>>
>> n <- 2250 #number of samples in time series
>> R <- matrix ((c ((cos(d)), (-sin(d)), (sin(d)), (cos(d)))), 2)
>> #rotation
>> matrix, where d is the resultant vector angle in degrees
>> V <- t (matrix ((c (Vx, Vy)), n)) #velocity matrix
>> Vadj <- R %*% (V) [, 1] #e.g. for the first Vx, Vy pair in the time-
>> series
>>
>> Now what I want to do is loop this to give me the solution at each
>> time-step
>> and then append the adjusted Vx and Vy time-series to a new matrix.
>> Can
>> someone please suggest how I should about this?
>>
>> Thanks,
>> Martin
>>
>>
>
> Perhaps the following will get what you want
>
> Vadj <- V %*% t(R)
>

? crossprod suggests that tcrossprod(V, R) is to be slightly preferred.

Cheers,
Michael




More information about the R-help mailing list