Skip to content
Prev 303567 / 398503 Next

specific matrix element tranformation

Hello,

Inline

Em 17-08-2012 04:39, bantex escreveu:
You don't need to say that 'b' is a matrix a second time! And this form 
is wrong, you should add 'byrow = TRUE' since you're using row order.
With your data, you would have two errors in applying function abc to 
matrix 'a'. Try the following.

fun <- function(a){
     b <- matrix(nrow = 3, ncol = 3)
     #let's say these are the transformations i wish to perform
     b[1,1] <- a[1,1]+1
     b[1,2] <- a[2,1]*a[2,2]
     b[1,3] <- a[2,2]+a[1,1]
     b[2,1] <- a[1,1]-5
     if(a[2,2] < 0){
         warning("a[2, 2] is negative, using zero for its square root 
b[2,2].")
         b[2,2] <- 0
     }else{
         b[2,2] <- sqrt(a[2,2])
     }
     if(a[2,2] == 0){
         warning("a[2, 2] is zero, using zero for division result b[2,3].")
         b[2,3] <- 0
     }else{
         b[2,3] <- a[1,1]/a[2,2]
     }
     b[3,1] <- a[2,2]-3
     b[3,2] <- a[1,1]*(a[1,2]+a[2,2])
     if(a[1,2] == 0){
         warning("a[1, 2] is zero, using zero for division result b[3,3].")
         b[3,3] <- 0
     }else if(a[1,1]/a[1,2] < 0){
         warning("a[1,1]/a[1,2] is negative, using zero for its square 
root b[3,3].")
         b[3,3] <- 0
     }else{
         b[3,3] <- sqrt(a[1,1]/a[1,2])
     }
     b
}

set.seed(2)
a <- matrix(rnorm(4),ncol = 2)
fun(a)