Multiply Matrix by Vector in R
A matrix is a 2-dimensional structure whereas a vector is a one-dimensional structure. In this article, we are going to multiply the given matrix by the given vector using R Programming Language. Multiplication between the two occurs when vector elements are multiplied with matrix elements column-wise.
- Create a matrix
- Create a vector
- Multiply them
- Display result.
Method 1: Naive method
Once the structures are ready we directly multiply them using the multiplication operator(*).
This code has both matrix and vector has equal size
Method 2: Using sweep()
we can use sweep() method to multiply vectors to a matrix. sweep() function is used to apply the operation “+ or – or ‘*’ or ‘/’ ” to the row or column in the given matrix.
sweep(data, MARGIN, FUN)
- data=input matrix
- MARGIN: MARGIN = 2 means row; MARGIN = 1 means column.
- FUN: The operation that has to be done (e.g. + or – or * or /)
Here, we are performing “*” operation