Write a R program to create a 5 x 4 matrix , 3 x 3 matrix with labels and fill the matrix by rows and 2 × 2 matrix with labels and fill the matrix by columns

1. Introduction

This R program demonstrates how to create matrices of different dimensions and fill them in specific ways. It includes a 5x4 matrix filled by columns, a labeled 3x3 matrix filled by rows, and a labeled 2x2 matrix filled by columns.

2. Program Steps

1. Create a 5x4 matrix and fill it by columns.

2. Create a 3x3 matrix with labels and fill it by rows.

3. Create a 2x2 matrix with labels and fill it by columns.

4. Print all three matrices.

3. Code Program

# Step 1: Create a 5x4 matrix filled by columns
matrix_5x4 <- matrix(1:20, nrow = 5, ncol = 4)

# Step 2: Create a 3x3 matrix with labels, filled by rows
row_names_3x3 <- c("Row1", "Row2", "Row3")
col_names_3x3 <- c("Col1", "Col2", "Col3")
matrix_3x3 <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE, dimnames = list(row_names_3x3, col_names_3x3))

# Step 3: Create a 2x2 matrix with labels, filled by columns
row_names_2x2 <- c("Row1", "Row2")
col_names_2x2 <- c("Col1", "Col2")
matrix_2x2 <- matrix(1:4, nrow = 2, ncol = 2, dimnames = list(row_names_2x2, col_names_2x2))

# Step 4: Print the matrices
print("5x4 Matrix:")
print(matrix_5x4)
print("3x3 Matrix with labels (filled by rows):")
print(matrix_3x3)
print("2x2 Matrix with labels (filled by columns):")
print(matrix_2x2)

Output:

5x4 Matrix:
[Matrix content]
3x3 Matrix with labels (filled by rows):
[Matrix content with row and column labels]
2x2 Matrix with labels (filled by columns):
[Matrix content with row and column labels]

Explanation:

1. matrix(1:20, nrow = 5, ncol = 4): Creates a 5x4 matrix filled by columns with numbers from 1 to 20.

2. matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE, dimnames = list(row_names_3x3, col_names_3x3)): Creates a labeled 3x3 matrix filled by rows with numbers from 1 to 9.

3. matrix(1:4, nrow = 2, ncol = 2, dimnames = list(row_names_2x2, col_names_2x2)): Creates a labeled 2x2 matrix filled by columns with numbers from 1 to 4.

4. print("5x4 Matrix:"): Prints the message indicating the 5x4 matrix.

5. print(matrix_5x4): Displays the 5x4 matrix.

6. print("3x3 Matrix with labels (filled by rows):"): Prints the message indicating the labeled 3x3 matrix filled by rows.

7. print(matrix_3x3): Displays the labeled 3x3 matrix.

8. print("2x2 Matrix with labels (filled by columns):"): Prints the message indicating the labeled 2x2 matrix filled by columns.

9. print(matrix_2x2): Displays the labeled 2x2 matrix.


Comments