1. LON-CAPA Logo
  2. Help
  3. Log In
 

Browsing resource, all submissions are temporary.


Vectorize a Function

A function f is defined by the following R function.

f <- function(x) {
    kpi <- (1:100)*pi
    ak <- 8/kpi^2*(c(0,-1,0,1) - 2/kpi*c(1,0,-1,0))
    2/3+sum(ak*cos(kpi*0.5*x))
}

Suppose we want to see what f(x) looks like. The simplest method is to use the curve() function to plot it. However, it only works if the function f(x) is vectorized, meaning that if x is a vector, the output of f(x) should be a vector of the same length as x. For example, if x is c(4.2, -1.4, 3.6), f(x) should return c(f(4.2), f(-1.4), f(3.6)). However, the function f defined above only works for a single value of x. If x is a vector, in the last line of the function x, ak and kpi are all vectors and R first tries to turn the expression inside the sum into a single vector and then sum over it, returning a single number instead of a numeric vector of the same length as x.

The simplest way to vectorize a function is to use the Vectorize() command mentioned at the end of Chapter 18 of Peng's textbook. For example, we can create a vectorized version of f(x) using the following command.

vecf <- Vectorize(f)

You can verify that vecf(c(4.2, -1.4, 3.6)) returns c(f(4.2), f(-1.4), f(3.6)), as expected.

a. (1 point) Use the curve() function to plot f(x) for x from -7 to 7 and then determine which of the following plots are closest to the graph of f(x). (If you forget how curve() works, review Week 3's notes.)

dynamically generated plot


dynamically generated plot


dynamically generated plot


dynamically generated plot


dynamically generated plot

The graph of f(x) is closest to





 Tries 0/1

b. (4 points) Another method to vectorize the function is to modify the last line of f(x). Consider the following modification of f(x).

vecf2 <- function(x) { 
    kpi <- (1:100)*pi
    ak <- 8/kpi^2*(c(0,-1,0,1) - 2/kpi*c(1,0,-1,0))
    MISSING CODE
}

What could the MISSING CODE be? Make sure you've checked that you get the same graph of f(x). (Select all that apply)
sapply(x, 2/3+sum(ak*cos(kpi*0.5*x)))
vapply(x, 2/3+sum(ak*cos(kpi*0.5*x)), numeric(1))
sapply(x, function(z) 2/3+sum(ak*cos(kpi*0.5*z)))
lapply(list(x,kpi,ak), function(z) 2/3+sum(ak*cos(kpi*0.5*z)))
tapply(x, c(kpi,ak), 2/3+sum(ak*cos(kpi*0.5*x)))
lapply(x, list(kpi,ak), 2/3+sum(ak*cos(kpi*0.5*x)))
vapply(x, function(z) 2/3+sum(ak*cos(kpi*0.5*z)), numeric(1))
apply(x, c(kpi,ak), 2/3+sum(ak*cos(kpi*0.5*x)))
replicate(x, 2/3+sum(ak*cos(kpi*0.5*x)))

 Tries 0/3