Write a R program to concatenate two given matrices of same column but different rows

1. Introduction

This R program concatenates two matrices that have the same number of columns but different numbers of rows. The result is a single matrix that combines the rows of both matrices.

2. Program Steps

1. Create the first matrix.

2. Create the second matrix, ensuring it has the same number of columns as the first.

3. Concatenate the two matrices into one.

4. Print the concatenated matrix.

3. Code Program

# Step 1: Create the first matrix
matrix1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)

# Step 2: Create the second matrix with the same number of columns
matrix2 <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 3, ncol = 3)

# Step 3: Concatenate the matrices
concatenated_matrix <- rbind(matrix1, matrix2)

# Step 4: Print the concatenated matrix
print("Concatenated Matrix:")
print(concatenated_matrix)

Output:

Concatenated Matrix:
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
[3,]    7    9   11
[4,]    8   10   12
[5,]    7    9   11

Explanation:

1. matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3): Creates the first matrix with 2 rows and 3 columns.

2. matrix(c(7, 8, 9, 10, 11, 12), nrow = 3, ncol = 3): Creates the second matrix with 3 rows and 3 columns.

3. rbind(matrix1, matrix2): Concatenates the first and second matrices row-wise.

4. print("Concatenated Matrix:"): Prints a message indicating the concatenated matrix.

5. print(concatenated_matrix): Displays the concatenated matrix.


Comments