In this tutorial, we will learn how to multiply a matrix by a constant in R. Matrix multiplication by a constant, also known as scalar multiplication, involves multiplying each element of the matrix by a constant value.
This is a common operation in linear algebra and is widely used in various applications such as data manipulation, computer graphics, and machine learning.
Step 1: Create a Matrix in R
First, we will create a matrix in R using the matrix() function. This function takes in a vector of values, and we can specify the number of rows and columns for the resulting matrix.
1 2 |
mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) print(mat) |
[,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6
We have created a 2×3 matrix named mat where the numbers 1 through 6 are arranged in two rows and three columns.
Step 2: Multiply the Matrix by a Constant
Now that we have our matrix, let’s multiply it by a constant. In R, you simply multiply the matrix by the constant using the * operator. For example, let’s multiply the matrix by the constant 3.
1 2 3 4 |
constant <- 3 result <- mat * constant print(result) |
[,1] [,2] [,3] [1,] 3 9 15 [2,] 6 12 18
As you can see, each element of the matrix has been multiplied by the constant value 3.
Step 3: Verify the Result
To verify that the result is correct, you can think of the constant as a 1×1 matrix with a value equal to the constant. Then, perform the element-wise multiplication of the matrices.
We can achieve this by defining the constant as a 1×1 matrix using the matrix() function and performing element-wise multiplication using the sweep() function.
1 2 3 4 |
constant_matrix <- matrix(constant, nrow = 1, ncol = 1) output <- sweep(mat, 1, constant_matrix, "*") print(output) |
[,1] [,2] [,3] [1,] 3 9 15 [2,] 6 12 18
The output is the same as before, which confirms that multiplying a matrix by a constant works as expected.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Create a matrix mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) print(mat) # Multiply the matrix by a constant constant <- 3 result <- mat * constant print(result) # Verify the result using sweep function constant_matrix <- matrix(constant, nrow = 1, ncol = 1) output <- sweep(mat, 1, constant_matrix, "*") print(output) |
Conclusion
In this tutorial, we learned how to multiply a matrix by a constant in R. We created a matrix using the matrix() function, multiplied the matrix by a constant using the * operator, and verified the result using the sweep() function.
Scalar multiplication is fundamental in linear algebra, and its implementation in R is straightforward and intuitive.