user2373707
user2373707

Reputation: 105

how to write a function for the product of two matrices

there are two matrices, A and B: enter image description here

the product of them is C=AB: enter image description here

now I want to write a function with a loop which returns C, the product. and it should return Error when the dimension of both matrices are not compatible. and the function should contain the two matrices A and B

I've never written functions with matrices, so I'm thankful for any help!

thanks so much for your help! now another question, if given enter image description here

would it still be possible to use the loop?

Upvotes: 0

Views: 424

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174863

Here's an R version as per how you tagged the Q:

multmat <- function(m1, m2) {
  if(!isTRUE(all.equal(dim(m1), dim(m2))))
    stop("Dimensions of matrices don't match.")
  m1 * m2
}

The function doing the multiplication is already done for you, it is *, but if you want the check, then you need a wrapper as a show above. In R, you don't want to do this via a loop.

This gives

m1 <- matrix(1:9, ncol = 3)
m2 <- matrix(1:9, ncol = 3)
multmat(m1, m2)

> multmat(m1, m2)
     [,1] [,2] [,3]
[1,]    1   16   49
[2,]    4   25   64
[3,]    9   36   81

m3 <- matrix(1:12, ncol = 3)
multmat(m1, m3)

> multmat(m1, m3)
Error in multmat(m1, m3) : Dimensions of matrices don't match.

Regarding the edit which adds a new problem, the %*% operator will give the matrix multiplication. E.g.

> m1 %*% m2
     [,1] [,2] [,3]
[1,]   30   66  102
[2,]   36   81  126
[3,]   42   96  150

Of course, now the restriction on the dimensions matching is different to the * case above, as shown below

> m1 %*% m3
Error in m1 %*% m3 : non-conformable arguments
> m1 %*% t(m3) ## transpose of m3
     [,1] [,2] [,3] [,4]
[1,]   84   96  108  120
[2,]   99  114  129  144
[3,]  114  132  150  168

The operation using the transpose of m3 works because it now has as many rows and m1 has columns.

Upvotes: 3

Related Questions