To perform scalar multiplication on a matrix in R, you simply multiply the matrix by a scalar value using the *
operator. This operation multiplies every element of the matrix by the scalar value.
In this example,
matrix
with values from 1 to 4 arranged in 2 rows and 2 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.scalar
and set it to 2.*
operator to multiply matrix
by scalar
. The multiplication is performed element-wise, meaning each element of the matrix is multiplied by the scalar.result_matrix
.result_matrix
to standard output to see the result of the scalar multiplication.matrix <- matrix(1:4, nrow = 2, ncol = 2)
scalar <- 2
result_matrix <- matrix * scalar
print(result_matrix)
[,1] [,2] [1,] 2 4 [2,] 6 8
In this example,
matrix
with values from 1 to 9 arranged in 3 rows and 3 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.scalar
and set it to 3.*
operator to multiply matrix
by scalar
. The multiplication is performed element-wise, meaning each element of the matrix is multiplied by the scalar.result_matrix
.result_matrix
to standard output to see the result of the scalar multiplication.matrix <- matrix(1:9, nrow = 3, ncol = 3)
scalar <- 3
result_matrix <- matrix * scalar
print(result_matrix)
[,1] [,2] [,3] [1,] 3 6 9 [2,] 12 15 18 [3,] 21 24 27
In this example,
matrix
with values from 1 to 16 arranged in 4 rows and 4 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.scalar
and set it to 4.*
operator to multiply matrix
by scalar
. The multiplication is performed element-wise, meaning each element of the matrix is multiplied by the scalar.result_matrix
.result_matrix
to standard output to see the result of the scalar multiplication.matrix <- matrix(1:16, nrow = 4, ncol = 4)
scalar <- 4
result_matrix <- matrix * scalar
print(result_matrix)
[,1] [,2] [,3] [,4] [1,] 4 8 12 16 [2,] 20 24 28 32 [3,] 36 40 44 48 [4,] 52 56 60 64
In this tutorial, we learned How to do Scalar Multiplication on a Matrix in R language with well detailed examples.