-1

I am currently using the %*% matrix multiplication function, however I wish to do the opposite (matrix division) and the %/% is for integer division. I have browsed online and haven't found a way to "undue" my matrix division, is there a built in function for this in R?

Cheers,

  • 2
    If you have two matrices, where normally one might do `m1 %*% m2`, can you do `m1 %*% 1/m2`? (You'll have to guard against zero-denominators.) – r2evans Jul 14 '20 at 05:23
  • 2
    Shouldn't the title of the question be "opposite of matrix multiplication"? – thelatemail Jul 14 '20 at 05:42
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 14 '20 at 05:46
  • My first comment is premature. First, the matrix dimensions will need to be jiggled, as the result of `m1 %*% m2` is not immediately something one can `%*%` back onto `m1` or `m2`. Also, if this were just straight multiple, that's one thing ... but matrix multiplication the linear-algebra way multiples a row with a column and then sums them up. I don't know that there's an easy method for *undoing* `sum(row1 * col1)` (etc). – r2evans Jul 14 '20 at 05:46
  • @r2evans Might be time to revisit your linear algebra books. ;) – Roland Jul 14 '20 at 06:15
  • Yeah, that's why I rushed to get that second comment in there ... I hastily posted the first comment, then realized that it was a little more than that ... nice answer, btw. – r2evans Jul 14 '20 at 06:16

2 Answers2

3

I believe you are looking for solve:

set.seed(42)
m1 <- matrix(rnorm(9), 3)
m2 <- matrix(rexp(9), 3)

m3 <- m1 %*% m2

m4 <- solve(m1, m3) #m3 "divided" by m1

all.equal(m2, m4)
#[1] TRUE

m5 <- m3 %*% solve(m2) #m3 "divided" by m2
all.equal(m1, m5)
#[1] TRUE

Of course, this can't be solved for all matrices m3 and m1 resp. m2 and better algorithms might exist depending on these matrices. Study some linear algebra.

Roland
  • 127,288
  • 10
  • 191
  • 288
0

I think you can use ginv from package MASS

set.seed(1)

A <- matrix(rnorm(10), 2)
B <- matrix(rnorm(30), 5)

C <- A %*% B

all.equal(A,C%*%MASS::ginv(B))
# [1] TRUE
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81