Combining Matrices in detail
Combining matrices involves merging two or more smaller matrices, either by rows or columns, to create a larger matrix. This operation is a fundamental data manipulation technique where the matrices involved must be of compatible dimensions. Matrices can be combined either horizontally or vertically.
Methods of Combining Matrices in R:
- Column-wise combination
- Row-wise combination
1. Column-Wise Combination
Column binding is performed using the cbind() function in R. It merges two matrices, A(m×n) and B(m×n), column-wise, provided they have the same number of rows.
Example:
# R program to combine two matrices column-wise
# Creating the first matrix
X = matrix(c(2, 4, 6), nrow = 3, ncol = 1)
# Creating the second matrix
Y = matrix(c(8, 10, 12, 14, 16, 18), nrow = 3, ncol = 2)
# Displaying original matrices
print(X)
print(Y)
# Combining matrices
print(cbind(X, Y))
Output:
[,1]
[1,] 2
[2,] 4
[3,] 6
[,1] [,2]
[1,] 8 10
[2,] 12 14
[3,] 16 18
[,1] [,2] [,3]
[1,] 2 8 10
[2,] 4 12 14
[3,] 6 16 18
Here, the columns [8 10], [12 14], and [16 18] from matrix Y are appended to the column [2 4 6] of matrix X in order. This does not modify the original matrices.
Properties:
- The total number of columns in the resultant matrix equals the sum of columns from the input matrices.
- Non-Commutative: The order in which matrices are combined matters, meaning
cbind(A, B) ≠ cbind(B, A). - Associative:
cbind(cbind(A, B), C) = cbind(A, cbind(B, C)).
2. Row-Wise Combination
Row binding is done using the rbind() function in R. It merges two matrices, A_(m×p) and B_(n×p), row-wise, as long as they have the same number of columns.
Example:
# R program to combine two matrices row-wise
# Creating the first matrix
X = matrix(c(1, 3, 5, 7), nrow = 2, ncol = 2)
# Creating the second matrix
Y = matrix(c(9, 11, 13, 15), nrow = 2, ncol = 2)
# Displaying original matrices
print(X)
print(Y)
# Combining matrices
print(rbind(X, Y))
Output:
[,1] [,2]
[1,] 1 3
[2,] 5 7
[,1] [,2]
[1,] 9 11
[2,] 13 15
[,1] [,2]
[1,] 1 3
[2,] 5 7
[3,] 9 11
[4,] 13 15
In this case, the rows [9 11] and [13 15] from matrix Y are appended to the rows [1 3] and [5 7] of matrix X in order. The original matrices remain unchanged.
Properties:
- The total number of rows in the resultant matrix equals the sum of rows from the input matrices.
- Non-Commutative: The order in which matrices are merged affects the result, meaning
rbind(A, B) ≠ rbind(B, A). - Associative:
rbind(rbind(A, B), C) = rbind(A, rbind(B, C)).
Complexity Analysis:
- Time Complexity:
- Space Complexity: , where is the number of elements in the first matrix and is the number of elements in the second matrix.
Leave a Reply