Search code examples
rmatrix

Scalar Multiplication in R


I'm trying to perform simple scalar multiplication in R, but I'm running into a bit of an issue.

In linear algebra I would do the following:

scalar multiplication

Here's how I've implemented this in R:

A <- matrix(1:4, 2, byrow = TRUE)
c <- matrix(rep(3, 4), 2)
A * c

This produces the correct output, but creating the scalar matrix c will be cumbersome when it comes to larger matrices.

Is there a better way to do this?


Solution

  • In R the default is scalar. For matrix multiplication use %*%. t is transpose and solve will give you the inverse. Here are some examples:

    a = matrix(1:4,2,2)
    3 * a
    c(1:2) %*% a
    c(1:2) %*% t(a)
    solve(a)
    

    Here is a link: matrix algebra in R