evoalgs-r-practise/create_matrices.R
2024-04-30 10:03:37 +02:00

60 lines
1.6 KiB
R

# 1. Creating a matrix from a vector using the matrix() function
matrix1 <- matrix(1:9, nrow=3, ncol=3)
print("Matrix from Vector:")
print(matrix1)
# 2. Specifying row and column names at the time of creation
row_names <- c("Row1", "Row2", "Row3")
col_names <- c("Col1", "Col2", "Col3")
matrix2 <- matrix(1:9, nrow=3, ncol=3, dimnames=list(row_names, col_names))
print("Matrix with Row and Column Names:")
print(matrix2)
# 3. Creating a matrix by binding vectors column-wise using cbind()
vector1 <- 1:3
vector2 <- 4:6
vector3 <- 7:9
matrix3 <- cbind(vector1, vector2, vector3)
print("Column-Bound Matrix:")
print(matrix3)
# 4. Creating a matrix by binding vectors row-wise using rbind()
matrix4 <- rbind(vector1, vector2, vector3)
print("Row-Bound Matrix:")
print(matrix4)
# 5. Creating a diagonal matrix using diag()
diagonal_matrix <- diag(c(1, 2, 3))
print("Diagonal Matrix:")
print(diagonal_matrix)
# 6. Creating a matrix of zeros
zero_matrix <- matrix(0, nrow=3, ncol=3)
print("Zero Matrix:")
print(zero_matrix)
# 7. Creating a matrix of ones
one_matrix <- matrix(1, nrow=3, ncol=3)
print("One Matrix:")
print(one_matrix)
# 8. Creating an identity matrix
identity_matrix <- diag(1, 3)
print("Identity Matrix:")
print(identity_matrix)
# 9. Using outer to create a matrix from two vectors
matrix5 <- outer(1:3, 1:3, FUN="*")
print("Matrix from Outer Product:")
print(matrix5)
# 9.5: using the byrow
matrix6 <- matrix(1:9, nrow=3, ncol=3, byrow=TRUE)
print("Matrix by Row:")
print(matrix6)
# 10. Creating a matrix with random numbers
random_matrix <- matrix(runif(9), nrow=3)
print("Matrix with Random Numbers:")
print(random_matrix)