# Create functional data with a linear relationship
set.seed(42)
t <- seq(0, 1, length.out = 50)
X <- matrix(0, 100, 50)
for (i in 1:100) X[i, ] <- sin(2*pi*t) * i/100 + rnorm(50, sd = 0.1)
beta_true <- cos(2*pi*t)
y <- X %*% beta_true + rnorm(100, sd = 0.5)
fd <- fdata(X, argvals = t)
# Cross-validate to find optimal number of PCs
cv_result <- fregre.pc.cv(fd, y, ncomp.range = 1:10)
Run the code above in your browser using DataLab