VOOZH about

URL: https://www.geeksforgeeks.org/r-language/multiply-matrix-by-vector-in-r/

⇱ Multiply Matrix by Vector in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Multiply Matrix by Vector in R

Last Updated : 26 Mar, 2021

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:

  • 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(*).

Example:

Output:

👁 Image

Example 2:

Output:

👁 Image

Example 3:

This code has both matrix and vector has equal size

Output:

👁 Image

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.

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:

👁 Image

Example 2:

Output:

👁 Image
Comment

Explore