s-news
[Top] [All Lists]

Re: Exchanging Indices of a Matrix

To: "Quinn, David" <David.Quinn@nrgenergy.com>
Subject: Re: Exchanging Indices of a Matrix
From: Sundar Dorai-Raj <sundar.dorai-raj@pdf.com>
Date: Tue, 25 Jun 2002 12:43:34 -0500
Cc: s-news@lists.biostat.wustl.edu
Organization: PDF Solutions, Inc.
References: <53173E7EC9822349ACC7FBEC177BDDDA18C34D@hqmail2.nrgenergy.com>
David,

> 
> Is there an easy way to do the following without the looping?  I'm guessing 
> not, since I think the internal representation of a matrix is as a list.    
> -- Thanks, David
> 
> for (i in 1:x)
> {
>         for (j in 1:y)
>         {
>                 for (k in 1:z)
>                 {
>                         new.matrix[k,j,i] <- old.matrix[i,j,k]
>                 }
>         }
> }

Looks like you need transpose. Or do you need something more general?

> A <- array(1:24,dim=c(2,3,4))
> B <- array(rep(NA,24),dim=c(4,3,2))
> for(i in 1:2) {
+   for(j in 1:3) {
+     for(k in 1:4) {
+       B[k,j,i] <- A[i,j,k] # your way
+     }
+   }
+ }
> 
> C <- t(A) # transpose
> all.equal(C,B)
[1] T
> 

-- 
Sundar Dorai-Raj, Ph.D.     
Statistical Methods Engineer
PDF Solutions, Inc.
Dallas TX
(972) 889-3085 x216
(214) 392-7619 cell
sundar.dorai-raj@pdf.com
http://www.pdf.com/


<Prev in Thread] Current Thread [Next in Thread>