Homework 1

library(gifski)

One of the most useful applications for linear algebra in data science is image manipulation. We often need to compress, expand, warp, skew, etc. images. To do so, we left multiply a transformation matrix by each of the point vectors.
For this assignment, build the first letters for both your first and last name using point plots in R. For example, the following code builds an H.

# write the initial of EX
x <- c(rep(0,500), seq(0,0, length.out = 1000), # vertical line - E
       rep(0,500), seq(0,1, length.out = 1000), # first horizontal line - E
       rep(0,500), seq(1,0, length.out = 1000), # second horizontal line - E
       rep(0,500), seq(0,1, length.out = 1000), # third horizontal line - E
       rep(0,500), seq(2,3, length.out = 1000), # first diagonal - X
       rep(0,500), seq(2,3, length.out = 1000)) # second diagonal - X 

y <- c(rep(0,500), seq(-1,1, length.out=1000), # vertical line - E
       rep(0,500), seq(1,1, length.out = 1000), # first horizontal line - E
       rep(0,500), seq(0,0, length.out = 1000), # second horizontal line - E
       rep(0,500), seq(-1,-1, length.out = 1000), # third horizontal line - E
       rep(0,500), seq(-1,1, length.out = 1000), # first diagonal - X
       rep(0,500), seq(1,-1, length.out = 1000)) # second diagonal - X

# matrix
z = rbind(x, y)

# intital plot
plot(y~x, xlim=c(-1,4), ylim=c(-2,2), col = "lightblue",
     main = "Initials")

Then, write R code that will left multiply (%*%) a square matrix (x) against each of the vectors of points (y). Initially, that square matrix will be the Identity matrix.
Use a loop that changes the transformation matrix incrementally to demonstrate the change

Shear

# shear effect in a for loop
for (val in seq(-3,3,length.out=50)) {
  shear_matrix <- matrix(c(2, 0, val, 1), nrow=2, ncol=2)
  shear_m <- apply(z, 2, function(x) x %*% shear_matrix)
  plot(shear_m[2,] ~ shear_m[1,], xlim=c(-6, 6), ylim=c(-6, 6), col = "lightblue")}

Scaling

for (val in seq(-3,3,length.out=50)) {
  scale_matrix <- matrix(c(val, 0, 0, val), nrow=2, ncol=2)
  scale_m <- apply(z, 2, function(x) x %*% scale_matrix)
  plot(scale_m[2,] ~ scale_m[1,], xlim=c(-6,6), ylim=c(-6,6), col = "lightblue")}

Rotation

for (val in seq(-3,3,length.out=50)) {
  rotate_z <- rbind(z, numeric(3000))
  rotate_matrix <- matrix(c(cos(val), sin(val), 0, -sin(val), cos(val), 0, 0, 0, 1), nrow=3, ncol=3)
  rotate_m <- apply(rotate_z, 2, function(x) x %*% rotate_matrix)
  plot(rotate_m[2,] ~ rotate_m[1,], xlim=c(-6,6), ylim=c(-6,6), col = "lightblue")}

Projection in animated fashion

for (val in seq(-3,3,length.out=50)) {
  projection_z <- rbind(z, numeric(3000))
  projection_matrix <- matrix(c(val,0,0,0,1,0,0,0,1), nrow=3, ncol=3)
  projection_m <- apply(projection_z, 2, function(x) x %*% projection_matrix)
  plot(projection_m[2,] ~ projection_m[1,], xlim=c(-6,6), ylim=c(-6,6), col = "lightblue")}