evoalgs-r-practise/intro/vectors_and_matrices.R

62 lines
1.7 KiB
R

# Create vectors
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)
# Basic Vector Operations
# -----------------------
# Element-wise addition
vector_add <- vector1 + vector2
print("Vector Addition:")
print(vector_add)
# Element-wise multiplication
vector_mult <- vector1 * vector2
print("Vector Multiplication:")
print(vector_mult)
# Dot product
dot_product <- sum(vector1 * vector2)
print("Dot Product:")
print(dot_product)
# Create Matrices
# ---------------
# Matrix from combining vectors as rows
matrix1 <- rbind(vector1, vector2)
print("Matrix from Vectors (Rows):")
print(matrix1)
# Matrix from combining vectors as columns
matrix2 <- cbind(vector1, vector2)
print("Matrix from Vectors (Columns):")
print(matrix2)
# Matrix and Vector Operations
# ----------------------------
# Adding a vector to each row of the matrix (by replicating the vector)
matrix_row_add <- matrix1 + vector1
print("Add Vector to Each Row of Matrix:")
print(matrix_row_add)
# Adding a vector to each column of the matrix (by replicating the vector)
matrix_col_add <- matrix2 + cbind(vector1)
print("Add Vector to Each Column of Matrix:")
print(matrix_col_add)
# Element-wise multiplication of a matrix by a vector
# Note: This operation requires conformable dimensions
matrix_element_mult <- matrix1 * cbind(vector1)
print("Element-wise Multiplication of Matrix by Vector:")
print(matrix_element_mult)
# Matrix multiplication by a vector
# This treats the vector as a column vector
matrix_vector_mult <- matrix1 %*% vector1
print("Matrix Multiplication by Vector:")
print(matrix_vector_mult)
# Transpose a matrix and multiply by a vector
# This treats the vector as a row vector
transpose_mult <- t(matrix1) %*% vector1
print("Transpose Matrix and Multiply by Vector:")
print(transpose_mult)