Skip to content
Prev 266662 / 398502 Next

Elegant way to subtract matrix from array

On Wed, Jul 27, 2011 at 4:06 AM, steven mosher <moshersteven at gmail.com> wrote:
For the first one:

   matrix(c(t(A)) - c(t(S)), nrow(A), byrow = TRUE)

or this version which may seem a bit more complex but has the
advantage that it shows the general form of which both your questions
are special cases:

    ix <- 2:1
    aperm(array(c(aperm(A, ix)) - c(t(S)), dim(A)[ix]), ix)

Now, as mentioned, the answer to second question is the same except for ix:

    ix <- c(2, 1, 3)
    aperm(array(c(aperm(Z, ix)) - c(t(Q)), dim(Z)[ix]), ix)