![]() |
VOOZH | about |
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.
Approach:
Method 1: Naive method
Once the structures are ready we directly multiply them using the multiplication operator(*).
Example:
Output:
👁 ImageExample 2:
Output:
👁 ImageExample 3:
This code has both matrix and vector has equal size
Output:
👁 ImageMethod 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.
Syntax:
sweep(data, MARGIN, FUN)
Parameter:
- 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
Example:
Output:
👁 ImageExample 2:
Output:
👁 Image