Skip to content
Prev 132454 / 398506 Next

array addition

Try this:

"%add%" <- function(x1, x2)
  {
    dim1 <- dim(x1)
    dim2 <- dim(x2)

    seq1 <- list();for(i in 1:length(dim1)) seq1[[i]]=seq(dim1[i])
    filter1 <- paste(seq1, collapse=",") 
    cmd1 <- paste("out[", filter1, "]", sep="")
    seq2 <- list();for(i in 1:length(dim2)) seq2[[i]]=seq(dim2[i])
    filter2 <- paste(seq2, collapse=",")
    cmd2 <- paste("out[", filter2, "]", sep="")

    out <- array(0, dim=pmax(dim1,dim2)) 
    eval(parse(text=paste(cmd1, "<-", cmd1, "+ x1")))
    eval(parse(text=paste(cmd2, "<-", cmd2, "+ x2")))
    out
  }

x1 <- array(round(5*runif(30)), dim=c(2,3,5))
x2 <- array(round(5*runif(24)), dim=c(3,4,2))
x <- x1 %add% x2

You probably want to add a check to make the dimensions the same, and the 
code needs tidying, but you get the idea.

Regards,
Richie.

Mathematical Sciences Unit
HSL


r-help-bounces at r-project.org wrote on 19/12/2007 09:26:44:
http://www.R-project.org/posting-guide.html
------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}
Message-ID: <OF26D7C90C.C0898BAC-ON802573B6.003E42F9-802573B6.003EA279@hsl.gov.uk>
In-Reply-To: <3972DD82-222B-4640-B299-62D9BBF0D9F4@hsl.gov.uk>