<- matrix(c(1,5,8,3,4,0), nrow = 3, ncol = 2)
mat mat
[,1] [,2]
[1,] 1 3
[2,] 5 4
[3,] 8 0
Matrices in R are described by its rows and columns. To define a matrix, we may use the matrix
function in R.
<- matrix(c(1,5,8,3,4,0), nrow = 3, ncol = 2)
mat mat
[,1] [,2]
[1,] 1 3
[2,] 5 4
[3,] 8 0
Accessing elements of the matrix can be done using square brackets (with two index placeholders)
1,2] # first row, 2nd column mat[
[1] 3
3,2] mat[
[1] 0
Write an R snippet to create a \(10 \times 10\) matrix where each entry is the product of it’s row and column number. i.e. \(A_{i,j} = ij\).
<- array(0, dim = c(10,10))
M for (i in 1:10)
{for(j in 1:10)
{= i*j
M[i,j]
}
}# To check your solution
M
Write an R snippet that takes in a matrix and returns a vector with all the column sums.
(Hint: The solution to this problem can be painfully trivial or needlessly complicated.)
# Approach - 1
<- function(M)
column_Sums
{<- dim(M)
dims <- dims[2]
cols <- numeric(cols)
sums for(i in 1:cols)
{= sum(M[,i])
sums[i]
}return(sums)
}
<- array(1:12,dim = c(4,3))
M # Look at M
M
<- column_Sums(M)
sums # Look at column sums of M
sums
# Aliter (Lazy approach)
<- colSums(M)
sums
sums
# Remark: Try a benchmark code on both these solutions to the problem, the result may shock you!
Define a \(6 \times 6\) matrix where each entry is the sum of random roll of two fair dice.
<- function()
roll_two_dice
{<- sum(sample(1:6, 2, replace = TRUE))
sum_of_rolls return(sum_of_rolls)
}<- replicate(36, roll_two_dice())
values <- matrix(values, nrow = 6)
answer answer
Write an R function that takes any n x n matrix and returns the sum of the elements in the upper triangular part of the matrix (excluding the diagonal)
<- function(mat) {
sum_upper_triangular if (!is.matrix(mat) || nrow(mat) != ncol(mat)) {
stop("Input must be a square matrix")
}
<- nrow(mat)
n <- 0
sum_upper
for (i in 1:(n-1)) {
for (j in (i+1):n) {
<- sum_upper + mat[i, j]
sum_upper
}
}
return(sum_upper)
}
# Example usage
<- matrix(1:25, nrow = 5, ncol = 5)
mat
matsum_upper_triangular(mat)
Define a 6×6 matrix with each element being the product of its row and column indices. Extract the submatrix from rows 2 to 4 and columns 3 to 5, and then calculate its inverse.
<- matrix(0, nrow = 6, ncol = 6)
mat for (i in 1:6) {
for (j in 1:6) {
<- i * j
mat[i, j]
}
}
# Extract submatrix from rows 2 to 5 and columns 3 to 5
<- mat[2:4, 3:5]
submat
# Calculate the inverse of the submatrix
#inverse_submat <- solve(submat)
# Display the inverse
#inverse_submat
Define a 10×10 matrix with all elements being the number 7. Then, replace the diagonal elements with the first 10 powers of 2.
# Create a 10x10 matrix with all elements being 7
<- matrix(7, nrow = 10, ncol = 10)
mat
# Replace diagonal elements with the first 10 powers of 2
diag(mat) <- 2^(0:9)
# Display the matrix
mat
Create a function in R that takes two matrices as inputs and returns their Hadamard product (element-wise product).
<- function(mat1, mat2)
hadamard_product
{# Check if input matrices are of the same dimensions
if (dim(mat1) != dim(mat2)) {
stop("Input matrices must have the same dimensions")
}
# Get dimensions of matrices
<- nrow(mat1)
m <- ncol(mat1)
n
# Initialize result matrix
<- matrix(0, nrow = m, ncol = n)
result
# Compute Hadamard product element-wise
for (i in 1:m)
{for (j in 1:n)
{<- mat1[i, j] * mat2[i, j]
result[i, j]
}
}
return(result)
}
# Also mat1*mat2 works!
Write an R function that takes inputs n
and ρ
. The function should return an n x n
identity matrix with ρ
added to all non-diagonal elements.
<- function(n, rho)
add_rho_to_identity
{# Initialize an n x n matrix with zeros
<- matrix(0, nrow = n, ncol = n)
mat
# Fill the matrix to create an identity matrix with rho added to non-diagonal elements
for (i in 1:n)
{for (j in 1:n)
{if (i == j)
{<- 1 # Set diagonal elements to 1
mat[i, j] else {
} <- rho # Set non-diagonal elements to rho
mat[i, j]
}
}
}
return(mat)
}
Write an R function that takes a matrix input and returns a smaller matrix with only the intersection of even rows and even columns of the original matrix.
<- function(mat)
extract_even_rows_even_cols
{# Determine dimensions of the input matrix
<- nrow(mat)
nrow_mat <- ncol(mat)
ncol_mat
# Initialize variables to store indices of even rows and even columns
<- seq(2, nrow_mat, by = 2)
even_rows <- seq(2, ncol_mat, by = 2)
even_cols
# Extract submatrix containing only even rows and even columns
<- mat[even_rows, even_cols]
submat
return(submat)
}
#You can use for loop too
Define a 3-dimensional array with dimensions 5 × 5 × 5
where the entries are random normal numbers with mean 0 and standard deviation 1.
<- function(dim1 = 5, dim2 = 5, dim3 = 5)
generate_random_3d_array
{# Generate random normal numbers
<- rnorm(dim1 * dim2 * dim3, mean = 0, sd = 1)
data
# Create the 3-dimensional array
<- array(data, dim = c(dim1, dim2, dim3))
array_3d
return(array_3d)
}
Create a \(100\times100\) matrix Mat1
with \(ij\)th entry being \(i\mod j\) for \(i\geq j\) else \(j \mod i\). Check via code is the matrix is Symmetric?
{r}# Initialize a 100x100 matrix Mat1
<- 100
n <- matrix(0, nrow = n, ncol = n)
Mat1
# Fill in Mat1 according to the specified rules
for (i in 1:n)
{for (j in 1:n)
{if (i >= j)
{<- i %% j
Mat1[i, j] else {
} <- j %% i
Mat1[i, j]
}
}
}
# Check if Mat1 is symmetric
all.equal(Mat1, t(Mat1))
Create a function which given a number n returns a \(n\times n\) matrix in which each \(i^{th},j^{th}\) entry is sum of results on rolling a fair die \((i+j)\) times.
{r}<- function(k)
sum_of_throws
{# Simulate k throws of a fair die (each throw results in a number from 1 to 6)
<- sample(1:6, k, replace = TRUE)
throws
# Return the sum of these throws
return(sum(throws))
}
# Function to create an n x n matrix with each (i, j) entry as the sum of i+j dice throws
<- function(n)
dice_sum_matrix
{# Initialize the n x n matrix
<- matrix(0, nrow = n, ncol = n)
matrix_result
# Populate the matrix
for (i in 1:n)
{for (j in 1:n)
{<- sum_of_throws(i + j)
matrix_result[i, j]
}
}
return(matrix_result)
}