Assignment Week 1

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.

# Letter H
x = c(rep(0, 500), seq(0, 1, length.out = 1000), rep(1, 500))

y = c(seq(-1, 1, length.out = 500), rep(0, 1000), seq(-1, 1, length.out = 500))

z = rbind(x, y)

plot(y~x, xlim = c(-3, 3), ylim = c(-3, 3))

\(~\)

Initials

# LS
x <- c(rep(-2, 500),
       seq(-1, -2, length.out = 500),
       rep(-2, 500), 
       sin(seq(-pi * .3, pi * 2.3, length.out = 500)) / 2 + 0) # S plot


y <- c(seq(-2,1,length.out = 500),
       rep(-2, 500),
       seq(-2,1,length.out = 500),
       seq(-2,1,length.out = 500)) # S Plot

z = rbind(x, y)

plot(y ~ x, xlim = c(-3, 3), ylim = c(-3, 3))

\(~\)

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.

left_multiply <- function(x, y) {
  x %*% y
}
left_multiply(matrix(rep(seq(1, 3, length.out = 3), 3), nrow = 3, ncol = 3), diag(3))
##      [,1] [,2] [,3]
## [1,]    1    1    1
## [2,]    2    2    2
## [3,]    3    3    3

\(~\)

Use a loop that changes the transformation matrix incrementally to demonstrate 1) shear, 2) scaling, 3) rotation , and 4) projection in animated fashion.

\(~\)

Shear

\(~\)

for (i in seq(0, 4, length.out = 20)) {
  shear_z <- apply(z, 2, function(x) left_multiply(x, matrix(c(1, 0, i, 1), nrow = 2, ncol = 2)))
   plot(shear_z[2,] ~ shear_z[1,], xlim = c(-3, 3), ylim = c(-3, 3))
}

\(~\)

Scaling

for (i in seq(1, 4, length.out = 20)) {
  scaling_z <- apply(z, 2, function(x) left_multiply(x, matrix(c(i, 0, 0, i), nrow = 2, ncol = 2)))
   plot(scaling_z[2,] ~ scaling_z[1,], xlim = c(-3, 3), ylim = c(-3, 3))
}

\(~\)

Rotating

for (i in seq(0, pi * 2, length.out = 20)) {
  rotating_z <- apply(z, 2, function(x) left_multiply(x, matrix(c(cos(i), -sin(i), sin(i), cos(i)), nrow = 2, ncol = 2)))
   plot(rotating_z[2,] ~ rotating_z[1,], xlim = c(-3, 3), ylim = c(-3, 3))
}

\(~\)

Projection in Animated Fashion

for (i in seq(0, 2 * pi, length.out = 20)) {
  Z <- rbind(z, rep(0, ncol(z)))
  ani_z <- apply(Z, 2, function(x) left_multiply(x, matrix(c(1, 0, 0, 0, cos(i), -sin(i), 0, sin(i), cos(i)), nrow = 3, ncol = 3)))
   plot(ani_z[2,] ~ ani_z[1,], xlim = c(-3, 3), ylim = c(-3, 3))
}

\(~\)

References

\(~\)

*For Animation

*For Sine Curve