To perform element-wise operations on a matrix in R, you can use arithmetic operators like +
, -
, *
, and /
between matrices or between a matrix and a scalar.
In this example,
matrix1
and matrix2
using the matrix()
function. For matrix1
, we provide a vector of values c(1, 2, 3, 4)
and specify the number of rows as 2. Similarly, for matrix2
, we provide a vector of values c(5, 6, 7, 8)
and specify the number of rows as 2.+
to add matrix1
and matrix2
element-wise. The result is stored in a new variable called resultMatrix1
.print()
function to display the resulting matrix resultMatrix1
.matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
matrix2 <- matrix(c(5, 6, 7, 8), nrow = 2)
resultMatrix1 <- matrix1 + matrix2
print(resultMatrix1)
[,1] [,2] [1,] 6 9 [2,] 8 12
In this example,
matrix3
using the matrix()
function. We provide a vector of values c(1, 2, 3, 4, 5, 6, 7, 8, 9)
and specify the number of rows as 3.scalar
and set it to 2. This is the value by which each element of the matrix will be multiplied.*
to multiply matrix3
by scalar
. The result is stored in a new variable called resultMatrix2
.print()
function to display the resulting matrix resultMatrix2
.matrix3 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
scalar <- 2
resultMatrix2 <- matrix3 * scalar
print(resultMatrix2)
[,1] [,2] [,3] [1,] 2 8 14 [2,] 4 10 16 [3,] 6 12 18
In this tutorial, we learned How to do Element-Wise Operations in a Matrix in R language with well detailed examples.