Skip to content

Instantly share code, notes, and snippets.

@kebbbnnn
Last active October 7, 2016 14:11
Show Gist options
  • Save kebbbnnn/cfeea97e331e165953ec8d694e9741f5 to your computer and use it in GitHub Desktop.
Save kebbbnnn/cfeea97e331e165953ec8d694e9741f5 to your computer and use it in GitHub Desktop.
# Problem 1
f1 <- function(n, k){
# initialize an nxn matrix with empty elements
mat <- matrix(ncol = n, nrow = n)
# evealuate the indices i and j
for(i in 1:nrow(mat)){
for(j in 1:ncol(mat)){
# assign values
mat[i, j] = if(i == j) k else if(j == i +1 || i == j + 1) 1 else 0
}
}
return(mat)
}
# test inputs for prob 1
print(f1(10, 2))
# Problem 2
f2 <- function(a = a %% 360){
return(floor((((if( a < 0) a + 360 else a)/90) %% 4) + 1))
}
# test inputs for prob 2
print(f2(45))
print(f2(90))
print(f2(180))
print(f2(270))
print(f2(360))
# Problem 3
f3 <- function(m){
for(i in 1:nrow(m)){
for(j in 1:ncol(m)){
m[i,j] = if(m[i,j] %% 2 != 0) m[i,j]*2 else m[i,j]
}
}
return(m)
}
# test inputs for prob 3
N <- matrix(c(c(1,5,-2),c(1,2,-1),c(3,6,-3)), ncol = 3, nrow = 3)
print(N)
print(f3(N))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment