Skip to content

array addition

3 messages · robin hankin, N. Lapidus

#
Hi

suppose I have two arrays x1,x2 of dimensions a1,b1,c1 and
a2,b2,c2 respectively.

I want  x = x1   "+"   x2 with dimensions c(max(a1,a2), max(b1,b2),max 
(c1,c2))

with

x[a,b,c] = x1[a1,b1,c1] + x2[a2,b2,c2] if    a <=min(a1,a2) , b<=min 
(b1,b2), c<=min(c1,c2)

and the other bits either x1 or x2 or zero according to whether the  
coordinates
are "in range" for x1 or x2 or neither.

The answer has to work for arbitrary-dimensioned arrays.

toy example follows (matrices):


 > x1
      [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
 > x2
      [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
 > x
      [,1] [,2] [,3] [,4] [,5]
[1,]    2    7   12    7    9
[2,]    4    9   14    8   10
[3,]    3    6    9    0    0
 >


Note the zeros at lower-right.


Is there a ready-made solution to this?





--
Robin Hankin
Uncertainty Analyst and Neutral Theorist,
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743
1 day later
#
[snip snip snip]
[snip snip snip]

perhaps it wouldn't be too much to ask for you to
check the most recent version of the "magic" package?

[and we *really* don't want any whingeing about
magic_1.3-31 not being available.  If I were you, I'd
email the package maintainer and tell him to release
updates in a more timely manner. . . ]





 > library(magic)
 > aplus
function (...)
{
     args <- list(...)
     if (length(args) == 1) {
         return(args[[1]])
     }
     if (length(args) > 2) {
         jj <- do.call("Recall", c(args[-1]))
         return(do.call("Recall", c(list(args[[1]]), list(jj))))
     }
     a <- args[[1]]
     b <- args[[2]]
     dima <- dim(a)
     dimb <- dim(b)
     stopifnot(length(dima) == length(dimb))
     out <- array(0, pmax(dima, dimb))
     return(do.call("[<-", c(list(out), lapply(dima, seq_len),
         list(a))) + do.call("[<-", c(list(out), lapply(dimb,
         seq_len), list(b))))
}
 >



--
Robin Hankin
Uncertainty Analyst and Neutral Theorist,
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743